Performance consideration for loops
Is there any significant performance problems between the two code snippets ?
User user
for(int i =0 ; i < 100 ; i++) {
user = new User() ;
}
and
for(int i =0 ; i < 开发者_如何学JAVA100 ; i++) {
User user = new User() ;
}
It's just about declaration.
There is a myth out there that this does make a difference, but the Java compiler is smart enough to make sure that it doesn't. This blog and this blog show the generated byte code between the two types of declarations. There isn't a significant performance difference.
The difference is what you find more readable.
No. Prefer the second one if user
is only used in the loop, but there is no performance difference.
Answer: exactly the same.
I created two class C1 and C2:
class C1 {
public void test() {
String user;
for(int i =0 ; i < 100 ; i++) {
user = new String("s" + i);
System.out.println(user);
}
}
}
And
class C2 {
public void test() {
for(int i =0 ; i < 100 ; i++) {
String user = new String("s" + i);
System.out.println(user);
}
}
}
After compiling them with "javac -source 1.4 -target 1.4" (or 1.3) and de-compile the classes, I got the same code:
import java.io.PrintStream;
class C1
{
C1()
{
}
public void test()
{
for(int i = 0; i < 100; i++)
{
String s = new String("s" + i);
System.out.println(s);
}
}
}
and
import java.io.PrintStream;
class C2
{
C2()
{
}
public void test()
{
for(int i = 0; i < 100; i++)
{
String s = new String("s" + i);
System.out.println(s);
}
}
}
Compiling them with "javac -source 1.5 -target 1.5" (or 1.6) and de-compile the classes, I got the same code too:
import java.io.PrintStream;
class C1
{
C1()
{
}
public void test()
{
for(int i = 0; i < 100; i++)
{
String s = new String((new StringBuilder()).append("s").append(i).toString());
System.out.println(s);
}
}
}
and
import java.io.PrintStream;
class C2
{
C2()
{
}
public void test()
{
for(int i = 0; i < 100; i++)
{
String s = new String((new StringBuilder()).append("s").append(i).toString());
System.out.println(s);
}
}
}
Creating the new object will be 99% of the time spent here. What you do in the loop or where you place the local variable is not important.
There shouldn't be a significant difference. In both loop bodies you allocate memory for a new User
.
The same question gets posted very often. What makes you think that it matters in any way where you declare the variable. 100 User Objects are created in both versions. Exactly the same code is generated.
The only difference is the scope of this variable, in version 1 you can access the variable User from outside the loop, in version 2 you can't. Depending on if this is wanted prefer the first or second version.
精彩评论