Given the following pieces of code, which one is more efficient? The real method returnSomething() can also return 0 in reality so try/catch is needed.
//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;
}
I was trying to figure out which piece of code is more efficient in terms of processor usage, they bot do the same thing. I would like to know if the code I wrote for testing is fit for the purpose or whether I can do other kind of testing on the code. My findings show that piece 2 is 9 times more efficient (9 times less time to execute) even though it uses hard-code if statements and the last if statement is always executed.
Full working program
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;
}
}
The first piece is probably slower because dividing is more expensive than comparing values.