nicholas
nicholas

Reputation: 3047

Performance Comparison of Passing Arrays in .NET

In C# (and presumably in VB.NET) there are three ways to pass constant-value arrays to a function, namely:

byte[] buffer = {0};
someFunction(buffer);

byte[] buffer = new byte[] {0};
someFunction(buffer);

someFunction(new byte[] {0});

Whereas simple typecasting an array declarator is invalid syntax:

someFunction((byte[]) {0});

Question:

What are the performance difference between the three working methods - in terms of CPU usage, memory allocation, and overall program size? Does the use of the new keyword have any effect on RAM usage or allocation, especially in cases where the declared variable falls out of scope immedately after the function call?

Upvotes: 0

Views: 248

Answers (5)

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

byte[] buffer = {0};

is simply a syntactic shortcut for

byte[] buffer = new byte[] {0};

and

someFunction(new byte[] {0});

is simply a syntactic shortcut for

byte[] some_tmp_variable_1 = new byte[] {0};
someFunction(some_tmp_variable_1);

So, as the others have concluded, you are not in fact passing the array to the method in different ways – you are always performing the exact same operation: All three pieces of code allocate local stack storage for a reference, all three perform a heap allocation via new and initialise the array memory with the provided value. Lastly, all pass the array reference to the method by value.

Upvotes: 4

xlecoustillier
xlecoustillier

Reputation: 16351

The three first ones are exactly the same once compiled.

The fourth one is incorrect.

Upvotes: 1

VladL
VladL

Reputation: 13033

Besides the last example, your compiler will change all 3 first examples to the same code.

Upvotes: 3

Zbigniew
Zbigniew

Reputation: 27584

someFunction((byte[]) {0}); is just plain wrong syntax, all others all the same, only difference here is scope of your buffer variable.

There is no overhead.

Upvotes: 2

Eric J.
Eric J.

Reputation: 150108

All of these valid methods will pass an array exactly the same way. You demonstrate three ways to legally declare and initialize an array, and each time you pass that array to another method.

someFunction((byte[]) {0});

is simply not a valid declaration syntax.

Upvotes: 9

Related Questions