Java – create variables in advance to use (?) in the loop

Which of the two is more "effective":

for (int i = 0; i < 10; i++) {
    int x = i * 2;
}

Or –

int x;
for (int i = 0; i < 10; i++) {
    x = i * 2;
}

(just an example)

I know they are essentially different - so please don't solve their differences

What if both prove to do the same thing - creating an X variable multiple times is a less efficient method, rather than just creating it once and simply reassigning its value?

Solution

No, in this case, there is no performance difference using the compiler

From a readability point of view, I prefer the first method, but this is something to be discussed elsewhere

However, as part of the reward for this answer:

for (int x = 0; x < calculateUserCountFromDatabaSEOrSomething(); x++) {
   //Do stuff
}

In the above example, this will be a performance problem, because the calculateUserCountFromDatabaSEOrSomething () method will be invoked in each iteration of the loop. This must be considered when writing software

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>