2

Which of the following code would be optimal for initializing array?

char szCommand[2048] ={0}

char szCommand[2048];
memset(szCommand,0,2048);
Maanu
  • 5,093
  • 11
  • 59
  • 82

5 Answers5

5

The second is not initializing the array, it's more like assigning to it. I think if ever there would be any noticeable difference (there won't be) you'd have to profile it yourself and see that the first version might be a tiiiiiny bit faster - but that's only when the optimizations are off. Premature optimization is the root of all evil - just DON"T think about it

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
3

The performance difference between the two versions would be so insignificant (if the compiler doesn't optimize away the difference) that I'd be inclined to go with the most readable one.

razlebe
  • 7,134
  • 6
  • 42
  • 57
2

Any decent compiler should emit the same code for both cases. In the case of memset, the compiler can eliminate the function call by understanding the semantics of the functions from the standard library.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
  • However, some compilers implement memset as an intrinsic, and it is also possible that the opposite is the case and the compiler will replace the first code sample with the second one. The memory must be cleared in both cases, anyways. – Sebastian Mach Jul 13 '11 at 10:29
2

For null terminated strings, in my opinion, the optimal initialization is this

szCommand[0] = 0;
Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
0

Both are same, first version is compact - that's it.

Ajay
  • 18,086
  • 12
  • 59
  • 105