Radek
Radek

Reputation: 15

Array memory allocation in C#

I was wandering which way of doing below code is better :

a)

    byte[] tmp = BitConverter.GetBytes(Number)

b) 
    byte[] tmp = new byte[sizeof(Number)]
    tmp = BitConverter.GetBytes(Number)

Is it necessary to use dynamic memory allocation ?

Upvotes: 0

Views: 137

Answers (3)

Steve
Steve

Reputation: 7271

The first is better for two reasons:

  1. It is more readable
  2. In sample b the first allocation is thrown away as tmp is re-assigned to the return value of GetBytes

Upvotes: 1

dcastro
dcastro

Reputation: 68660

Definitely a).

b) creates two arrays, the first of which is completely unnecessary and is thrown away right after being initialized.

Upvotes: 4

Selman Genç
Selman Genç

Reputation: 101681

Actually second one is redundant, because GetBytes returns a new array so you are throwing away the first array you created...

Upvotes: 2

Related Questions