给定以下代码,哪一个更有效?真正的方法 returnSomething() 在现实中也可以返回 0,因此需要 try/catch。
//piece one
long sleepTime = 200;
try{ sleepTime /= returnSomething();}
catch(Exception e){sleepTime = 200;}
private int returnSomething(){
return 1;
}
//or
//piece two
long sleepTime = 200;
if(returnSomething() == 3){sleepTime = 67;}
else if(returnSomething() == 2){sleepTime = 100;}
else if(returnSomething() == 1){sleepTime = 200;}
private int returnSomething(){
return 1;
}
我试图弄清楚哪一段代码在处理器使用方面更有效,它们机器人做同样的事情。我想知道我为测试编写的代码是否适合该目的,或者我是否可以对代码进行其他类型的测试。我的发现表明,第 2 部分的效率提高了 9 倍(执行时间减少了 9 倍),即使它使用硬代码 if 语句并且始终执行最后一个 if 语句。
完整的工作程序
public class CodePerformanceTester
{
public static void main(String[] args){
CodePerformanceTester tester = new CodePerformanceTester();
tester.start();
}
public void start(){
double start = System.currentTimeMillis();
long sleepTime = 200;
for(int i=0; i<10000000; i++){
//uncoment here the two lines below
//try{ sleepTime /= returnSomething();}
//catch(Exception e){sleepTime = 200;}
//coment the IF STATEMENTS when above code uncomented
if(returnSomething() == 3){sleepTime = 67;}
else if(returnSomething() == 2){sleepTime = 100;}
else if(returnSomething() == 1){sleepTime = 200;}
}
double end = System.currentTimeMillis();
System.out.println("Execution time for 10 million iteration was "+(end-start)+" ms.");
}
private int returnSomething(){
return 1;
}
}