循环时可能重复:
Which loop has better performance? Why?
Which is optimal ?
Efficiency of Java code with primitive types
,例如:
for ( int j = 0; j < 1000; j++) {};
我需要实例化1000个对象,当我声明循环内的对象从循环外声明它时,它有什么不同?
for ( int j = 0; j < 1000; j++) {Object obj; obj =}
vs
Object obj;
for ( int j = 0; j < 1000; j++) {obj =}
很明显,只能从循环范围或从它周围的范围访问该对象。但我不了解性能问题,垃圾收集等。
最佳做法是什么?谢谢
答案 0 :(得分:4)
第一种形式更好。限制变量的范围使读者更容易理解变量的使用位置和方式。
在性能方面,限制范围也有一些小优势,您可以在another answer.中阅读这些优点但这些问题仅次于代码理解。
答案 1 :(得分:0)
没有区别。编译器会将它们优化到同一个地方。
答案 2 :(得分:0)
我在我的机器上测试了这个问题,差异大约是2-4个超过10000个实例,我测试了所有类型的东西,比如你实例化并赋值:
int i=0;
与以下相比:
int i;
i=0;
这是我用于测试的代码,当然我更改了它进行测试,并且在机器达到优化之前有一个初始的平衡效果,一旦你测试就可以看清楚:
package initializer;
public final class EfficiencyTests {
private static class Stoper {
private long initTime;
private long executionDuration;
public Stoper() {
// TODO Auto-generated constructor stub
}
private void start() {
initTime = System.nanoTime();
}
private void stop() {
executionDuration = System.nanoTime() - initTime;
}
@Override
public String toString() {
return executionDuration + " nanos";
}
}
private static Stoper stoper = new Stoper();
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
theCycleOfAForLoop(100000);
theCycleOfAForLoopWithACallToSize(100000);
howLongDoesItTakeToSetValueToAVariable(100000);
howLongDoesItTakeToDefineAVariable(100000);
System.out.println("\n");
}
}
private static void theCycleOfAForLoop(int loops) {
stoper.start();
for (int i = 0; i < loops; i++);
stoper.stop();
System.out.println("The average duration of 10 cycles of an empty 'for' loop over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);
}
private static void theCycleOfAForLoopWithACallToSize(int loops) {
ArrayList<Object> objects=new ArrayList<Object>();
for (int i = 0; i < loops; i++)
objects.add(new Object());
stoper.start();
for (int i = 0; i < objects.size(); i++);
stoper.stop();
System.out.println("The average duration of 10 cycles of an empty 'for' loop with call to size over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);
}
private static void howLongDoesItTakeToSetValueToAVariable(int loops) {
int value = 0;
stoper.start();
for (int i = 0; i < loops; i++) {
value = 2;
}
stoper.stop();
System.out.println("The average duration of 10 cycles of setting a variable to a constant over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);
}
private static void howLongDoesItTakeToDefineAVariable(int loops) {
stoper.start();
for (int i = 0; i < loops; i++) {
int value = 0;
}
stoper.stop();
System.out.println("The average duration of 10 cycles of initializing and setting a variable to a constant over " + loops + " iterations is: " + stoper.executionDuration * 10 / loops);
}
private static void runAForLoopOnAnArrayOfObjects() {
// TODO Auto-generated method stub
}}
如果你减少另一个人的时间,你可以得出你需要多长时间......(如果你理解我的意思)
希望这可以节省你一些时间。
你需要了解的是,我测试了这些东西以优化我的平台的绘制更新循环并且它有所帮助。 亚当。