I was checking out this discussion: How slow are Java exceptions? and while experimenting, found out that if I run static methods instead of instance methods, the normal path actually takes more time than try-catch path.
What I m doing is: create a no-op static foo()
method, create static method method1()
that calls foo()
100000000 times normally, and another static method method2()
which calls foo()
100000000 times in a try-catch block. What I see is, method2
actually takes less time than method1
.
任何想法?
public class ExceptionsStatic
{
public static void main(String... args)
{
withNormal();
withTry();
}
static void foo()
{
}
static void foo2() throws Exception
{
}
static void withTry()
{
long t1 = System.currentTimeMillis();
for(int i = 0; i < 100000000; i++)
{
try
{
foo2();
}
catch(Exception e)
{
}
}
long t2 = System.currentTimeMillis();
System.out.println("try time taken " + (t2 - t1));
}
static void withNormal()
{
long t1 = System.currentTimeMillis();
for(int i = 0; i < 100000000; i++)
{
foo();
}
long t2 = System.currentTimeMillis();
System.out.println("normal time taken " + (t2 - t1));
}
}