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?
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.
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.
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.
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.
There's absolutely no difference between the two options. They are compiled to the identical IL code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With