T
tom fredriksen
Hi
I did a test to compare a task making lots of method calls to the same
operation in a loop, just to get a sense of the speed cost of method
calls. What i found was a bit strange. one would think the loop would be
the fastest solution, but in my example its actually the method call
that is faster. Does anybody have any ideas why that is? or if there is
something wrong with the code?
Are there any other factors than the speed of the jump and the time it
takes to allocate parameters on the stack that is relevant to the test?
/tom
import java.util.*;
public class BranchTest
{
private Random rand = new Random();
public int add(int sum)
{
return(sum + rand.nextInt(10));
}
public static void main(String args[])
{
{
BranchTest b = new BranchTest();
int count = Integer.parseInt(args[0]);
int total = 0;
long startTime = System.currentTimeMillis();
for(int c=0; c<count; c++) {
total = b.add(total);
}
long endTime = System.currentTimeMillis();
System.out.println("Elapsed time: " + (endTime - startTime));
}
{
Random rand = new Random();
int count = Integer.parseInt(args[0]);
int total = 0;
long startTime = System.currentTimeMillis();
for(int c=0; c<count; c++) {
total += rand.nextInt(10);
}
long endTime = System.currentTimeMillis();
System.out.println("Elapsed time: " + (endTime - startTime));
}
}
}
I did a test to compare a task making lots of method calls to the same
operation in a loop, just to get a sense of the speed cost of method
calls. What i found was a bit strange. one would think the loop would be
the fastest solution, but in my example its actually the method call
that is faster. Does anybody have any ideas why that is? or if there is
something wrong with the code?
Are there any other factors than the speed of the jump and the time it
takes to allocate parameters on the stack that is relevant to the test?
/tom
import java.util.*;
public class BranchTest
{
private Random rand = new Random();
public int add(int sum)
{
return(sum + rand.nextInt(10));
}
public static void main(String args[])
{
{
BranchTest b = new BranchTest();
int count = Integer.parseInt(args[0]);
int total = 0;
long startTime = System.currentTimeMillis();
for(int c=0; c<count; c++) {
total = b.add(total);
}
long endTime = System.currentTimeMillis();
System.out.println("Elapsed time: " + (endTime - startTime));
}
{
Random rand = new Random();
int count = Integer.parseInt(args[0]);
int total = 0;
long startTime = System.currentTimeMillis();
for(int c=0; c<count; c++) {
total += rand.nextInt(10);
}
long endTime = System.currentTimeMillis();
System.out.println("Elapsed time: " + (endTime - startTime));
}
}
}