Declaring an array before or inside a loop

Which is more efficient?

An array declaration, for example. char buffer [4096] before the loop and at each iteration clear its contents strlcpy or declare an array inside the loop with the initial value ""?

char buffer[4096] = ""; while(sth) { strlcpy(buffer,"",sizeof(buffer)); //some action; } 

vs

 while(sth) { char buffer[4096] = ""; //some action; } 
+4
source share
5 answers

There is probably no significant difference between the two. The only way to be sure that this is to compare or view the assembly generated by the compiler.

The second example is clearer and would be preferable.

+3
source

There is also no reason to flush the entire buffer if it is simply used as a string buffer. All you have to do is make sure that byte NUL \0 added to the end of the corresponding line.

If you want to ensure that str * functions begin at the beginning of buffer , a simple *buffer = '\0' is all that is needed for the reason mentioned above.

+3
source

The only possible difference in performance is a buffer assignment, and this will probably be translated by your compiler into a single statement that will be identical to this:

 *buffer = 0; 

Compilers will not perform stack control when entering a loop. Regardless of whether you specify a buffer inside or outside the loop, it makes no difference to the stack. The buffer space will be reserved on the stack at the beginning of the procedure, regardless of where you define your buffer variable (which does not mean that the compiler will allow you to access the buffer outside the area where it is defined).

Even the one job shown above is likely to be optimized by your compiler if it sees that it makes no sense to reinitialize the buffer each time again and again.

+1
source

I offer the first version. In the first version, an array is allocated only once. In the second version, the array is allocated with each iteration of the loop.

Although compilers can optimize allocation (for example, execute only once), I believe that factoring it tells the reader that memory is allocated only once.

This can be nothing to worry about, since many platforms are allocated on the stack, and distribution consists of changing the contents of the stack pointer.

With a dubious profile.

When considering optimization, do not do this. Spend time making the program right and reliable.

0
source

Source: https://habr.com/ru/post/1341220/


All Articles