0

Possible Duplicate:
memcpy vs assignment in C

I wanted to know if there is a gain in performance of assigning a big structure (e.g 100 bytes) automatic variable to zero rather than doing memset it to zero in run time in C. Not sure if gcc compiler can do optimization at compile time for this

Below are the two cases

Case 1:

void fun1()
{
   struct S y = {0};
}

Case 2:

void fun1()
{
  struct S y;
  memset(&y, 0, sizeof(y));
}
Community
  • 1
  • 1
Vaibhav
  • 37
  • 2
  • 3
    If you want to know which is faster, just time it yourself. If you're wondering *why* one is faster, show us the numbers and that'll make a much more interesting question. – Mysticial May 06 '12 at 05:53

2 Answers2

4

gcc will almost certainly handle this better than you can, and this is probably not a bottleneck in your system performance, so you shouldn't worry about trying to optimize this.

Oleksi
  • 12,947
  • 4
  • 56
  • 80
  • On the other hand, memset is highly optimized too. I would not be surprised if gcc uses it internally. I would agree that your best possible time with memset should be the same or longer than gcc's, though, so +1. – Sergey Kalinichenko May 06 '12 at 05:56
  • thanks for the response. I think I can safely assume that case 1 is anytime better than case 2 – Vaibhav May 06 '12 at 06:03
0

This is almost an exact duplicate of memcpy vs assignment in C

Assignment is almost always better than direct memory manipulation (not to mention more verbose). And code is, after all, meant to be read; not just written.

Community
  • 1
  • 1
David Titarenco
  • 32,662
  • 13
  • 66
  • 111