0

In C# when you create an array, it is initialized with default value for each element.

var array = new int[1000];
// array elements are initialized with 0 by default.

Although it is a very good behavior which prevents lots of bugs, but in some situations initializing elements by default value may be unnecessary and lead to some performance pitfalls. For example:

while (someCondition)
{
    var array = new int[10000];
    for (var i = 0; i < 10000; i++)
        array[i] = someMethod(i);
}

In this scenario the initialization of array is totally unnecessary and in some cases may cause performance issues.

Question: Is there anyway to create an array not initializing its elements by some value (so each element has some random number in it)?

9
  • Any initilization of array will require O(n) (linear). No way to avoid it. Commented Oct 21, 2015 at 11:10
  • 1
    This is a duplicate question. Answer is no, you can't. Commented Oct 21, 2015 at 11:11
  • And thank goodnes that you can't - the OS won't let you. That's one of the oldest hacks to read other processes' memory, which is why the OS will always give you clean memory pages. Which also means - no there is no performance penalty Commented Oct 21, 2015 at 11:14
  • In any case an array initialization has a O(n) complexity. You can create a nullable int array and set value to null to avoid bug, but in any case the complexity will be the same. var array = new int?[10000]; for (var i = 0; i < 10000; i++) array[i] = null; Commented Oct 21, 2015 at 11:21
  • 1
    @mehrandvd what is the actual problem you are trying to solve? Instead of avoiding initiallization, perhaps you should look at reusing buffers by using BufferManager. Another option is to declare the buffer outside the loop to avoid repeated object creation. This is costly even if the buffer data isn't initialized Commented Oct 21, 2015 at 11:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.