Which is better, to define the variable inside the loop or outside, with huge loop times

Viewed 103

I need to use an array in a loop, and the loop time is very huge.

Case 1: define the array outside the for-loop and pass it to fun2

void fun1(){
    int temp[16];
    for(int i = 0;i <times; i++)
    {
        fun2(temp);
    }       
}

void fun2(int[]& temp){
    /**  do something with temp*/
}

Case 2: define the array in fun2:

void fun1() {
    for (int i = 0; i < times; i++)
    {
        fun2();
    }
}

void fun2() {
    int temp[16];
    /**  do something with temp */
}

fun1 will be called very often. In this situation, which is better?

Does Case 2 have some influence on performance?

2 Answers

If you look for an answer to the general case, the answer is, "it depends." If you want an answer to your specific example, the answer is that the second version will be more efficient.

Ask yourself:

  1. Is there a cost to construction / destruction / reuse?

In your example, there is none (except adjusting the stack pointer, which is extremely cheap). But if it was an array of objects, or if you had to initialize the array to a specific value, that changes.

  1. How does the cost of parameterization factor in?

This is very minor but in your first case, you pass a pointer to the function. If the function is not inlined, this means that the array can only be accessed through that pointer. This takes up one register which could be used otherwise. In the second example, the array can be accessed through the stack pointer, which is basically free.

It also affects alias and escape analysis negatively which can lead to less efficient code. Basically, the compiler has to write values to memory instead of keeping them in registers if it cannot prove that a following memory read may not refer to the same value.

  1. Which version is more robust?

The second version ensures that the array is always properly sized. On the other hand, if you pass an object whose constructor may throw an exception, constructing outside the function may allow you to throw the exception at a more convenient location. This could be significant for exception safety guarantees.

  1. Is there a benefit in deallocating early?

Yes, allocation and deallocation are costly, but early destruction may allow some reuse. I've had cases where deallocating objects early allowed reuse of the memory in other parts of the code which improved use of the CPU cache.

depends on what you want to achieve..in this case, i'm assuming you are looking for performance which case 2 would be the better option as the function would create the variable on the fly instead of trying to get the variable globally then its value.

Related