Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it advised to declare variables inside loops?

As far as I know, declaring a variable inside a loop is less efficient than declaring outside and modify it inside the loop.

Example:

std::list<<double> l;
for(int i = 0; i < 100000; ++i)
{
    double a;
    a = 500.0 * i;
    l.append(a);
}

Another example with pointer:

std::list<<double *> l;
for(int i = 0; i < 100000; ++i)
{
    double* a;
    *a = 500.0 * i;
    l.append(a);
}

The examples don't have enough sense but I just want to show that the double and the pointer are being declared inside the loop.

The thing is, the scope of the variable is the same as the loop, so when the loop do an iteration, will it destroy the variable and then declaring it again? Or it just stays in the heap until the end of the for loop? How efficient is it to do that? Is it a waste of resources?

I code it as it was in C++.

Thanks in advance!

like image 920
Monetillo Avatar asked Jan 21 '26 20:01

Monetillo


1 Answers

In terms of memory usage, there is no difference in most implementations. A stack frame is typically created to accommodate all variables declared anywhere inside the function.

But if the type has a constructor and/or destructor, there might be additional overhead in calling it every loop iteration. And if that type allocates memory of its own (e.g. std::vector), then those allocations and deallocations are also going to happen each loop iteration, instead of only once.

That said, you should still start out by declaring the variable inside the loop if it's not needed for longer than one iteration! It's easy to forget to clear any previous value, and this can quickly lead to bugs. Much better to make it correct first, and optimize afterwards.

like image 105
Thomas Avatar answered Jan 23 '26 16:01

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!