New memory in every iteration

If we declare a variable inside the loop will it be allocated new memory every time?
Eg: for (int i = 0; i<5; i++) { int temp;}

@nehauppal9,
Yes, after every iteration new memory will be allocated. Overall performance won’t matter. Because, after every iteration, they memory will be free and the garbage collector will clear the memory.

Although, this is an excellent practice.
By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.

1 Like