Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variable type in a infinite loop performance? [duplicate]

Well according to some Stack Overflow question answers, I've read that using declaration of object inside the loop, is better than doing it outside of it, performance sided.

I could not understand why, because when I use the declaration inside the loop, my software uses more RAM then the one with the declaration outside of the loop.

while (true) {
    String hey = "Hello.";
}

Ram usage: 1820kb

String hey;
while (true) {
    hey = "Hello.";
}

Ram usage: 1720kb

Why people say that I should use the first loop cause its better for performance, yet it uses 100kb more from the ram?

like image 350
Artemkller545 Avatar asked Jan 14 '14 15:01

Artemkller545


People also ask

Is it bad to declare variables in a loop?

It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs.

Can I declare a variable inside a for loop Java?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Why is my for loop running infinitely?

An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.


2 Answers

When running code under release mode in .NET, the two pieces of code are identical due to a compiler optimization technique called loop invariant code motion. There are a huge number of smart optimization techniques in the JIT optimizer that will 'fix' your code. Therefore you should in principle favor readability/simplicity in code over anything else.

like image 109
Bas Avatar answered Sep 28 '22 03:09

Bas


There's absolutely no difference between the two options. They are compiled to the identical IL code.

like image 45
Thomas Weller Avatar answered Sep 28 '22 02:09

Thomas Weller