-3

Which is the optimized way?

1)

{
    int a[100] = {0};
}

or 2)

{
    int a[100];
    memset(a,0,100);
}

Assembly code generated by the two approches differ by how many instructions ?

Sam Hosseini
  • 813
  • 2
  • 9
  • 17
  • 5
    Why not simply look at the generated assembly code? Also, remember that different compiler optimization settings may change the generated code considerably. There's also the thing that on some platform, not all instructions are equal; Some may take longer than others, meaning that even if one piece of code contains more instructions it might actually be quicker. And lastly, you can be sure that the `memcpy` function will be extremely optimized. – Some programmer dude Dec 18 '14 at 13:32
  • Absolutely second one: it will take more or less 1/4 of 1st (when made compilable) method...LOL – Adriano Repetti Dec 18 '14 at 13:37
  • Thanks Aerofoil Kite. – Santhosh Kumar Dec 18 '14 at 13:43
  • Recent GCC on amd64 will generate the same assembly in both cases. – Piotr Praszmo Dec 18 '14 at 13:44

1 Answers1

1

They typically compile down to the same assembly code especially with optimizations turned on or, otherwise, with a simple loop (e.g rep stos). However, it depends on the context: you usually don't even need (although you think so) to zero an array.

I would definitely prefer the first version as it's less error prone and (imho) states clearly your intent.

edmz
  • 8,220
  • 2
  • 26
  • 45