English 中文(简体)
try固定方法
原标题:try-catch slowness for static methods in Java

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));
    }
}
最佳回答

I have modified your code a bit so the optimizer does not remove code. By running it several times in Sun/Oracle JVM the things I have found are:

  • Execution time is not deterministic. This is usual in HotSpot JVMs, especially in multicore systems
  • Differences between withNormal() and withTry are minimal. This is to be expected as no actual exception is ever thrown and there are no finally blocks.
  • The version that is run first tends to be slower. It might be something related to the HotSpot compiler "warming up", but I am not an expert in HotSpot internals

总之,如果在Sun/Oracle JVERS公司运行,最有可能从热电站获得噪音,我不会指望使用例外情况的代码之间有任何重大差别。

<>>>>>

我以<代码>-server和-client为旗号,除执行外,在我的机器中速度更快,适用上述意见。

经修改的法典如下:

public class ExceptionsStatic    {

public static void main(String... args)
{
    withNormal();
    withTry();
}

static int fooVar;
static void foo()
{
    fooVar++;
}

static int foo2Var;
static void foo2() throws Exception
{
    foo2Var++;
}

static void withTry()
{
    long t1 = System.currentTimeMillis();

    foo2Var = 0;
    for(int i = 0; i < 100000000; i++)
    {
        try
        {
            foo2();
        }
        catch(Exception e)
        {

        }
    }

    long t2 = System.currentTimeMillis();

    System.out.println("try time taken " + (t2 - t1) + "; " + foo2Var);
}

static void withNormal()
{
    long t1 = System.currentTimeMillis();

    fooVar = 0;
    for(int i = 0; i < 100000000; i++)
    {
        foo();
    }

    long t2 = System.currentTimeMillis();

    System.out.println("normal time taken " + (t2 - t1) + "; " + fooVar);
}
问题回答

我曾试图重订你的试验守则,然后通过 j。 归根结底,这些都是为了让你不必通过一个大的文字圈子roll。

请注意,如果国家机器设备公司根本不实行优化,则按 below木堆堆放场实施沥青编码。 因此,如果没有其他外部因素,执行<代码>method2(>> 包括附加指示(<编码>第11条:第15条)的时间更长。

当然,正如Joachim在下文提到的那样,斜体编码对业绩说得很少。

有许多旗帜可以用来进行特征分析,并促成/拆解联合核查机制的优化。 在线浏览。 关于1.4.2,我发现,link,后者也可与新的JRE公司合作。

加入: 在支持的考试和测验中,你可以通过使用以下证书旗帜<>-XX:-PrintCompilation,使国际交易日志能够追踪产出。


javap输出:

Ryan-Schippers-MacBook-Pro-2:Miscellaneous work$ javap -c -classpath ./src SlowTryCatch
Compiled from "SlowTryCatch.java"
public class SlowTryCatch extends java.lang.Object{
public SlowTryCatch();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   return

public static void foo();
  Code:
   0:   return

public static void method1();
  Code:
   0:   iconst_0
   1:   istore_0
   2:   iload_0
   3:   ldc #2; //int 100000000
   5:   if_icmpge   17
   8:   invokestatic    #3; //Method foo:()V
   11:  iinc    0, 1
   14:  goto    2
   17:  return

public static void method2();
  Code:
   0:   iconst_0
   1:   istore_0
   2:   iload_0
   3:   ldc #2; //int 100000000
   5:   if_icmpge   21
   8:   invokestatic    #3; //Method foo:()V
   11:  goto    15
   14:  astore_1
   15:  iinc    0, 1
   18:  goto    2
   21:  return
  Exception table:
   from   to  target type
     8    11    14   Class java/lang/Exception


}

这里是一个微小基准,其不足。 使用<代码>1或2>,作为方案参数和-XX:+PrintCompilation -verbose:class -verbose:gc作为通用公平市价参数。

public class TryBlockBenchmark {
    private static final int MEASUREMENTS = 100;
    private static int dummy = 0;

    public static void main(String[] args) {
        boolean tryBlock = args[0].equals("1");
        System.out.println(tryBlock ? "try block" : "no try block");

        for (int i = 0; i < MEASUREMENTS; i++) {

            long start = System.currentTimeMillis();
            if (tryBlock) {
                benchmarkTryBlock();
            } else {
                benchmarkNoTryBlock();
            }
            long end = System.currentTimeMillis();

            System.out.println((end - start) + " ms");
        }

        System.out.println("(" + dummy + ")");
    }

    private static void benchmarkTryBlock() {
        for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
            try {
                staticMethod();
            } catch (Exception e) {
            }
        }
    }

    private static void benchmarkNoTryBlock() {
        for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
            staticMethod();
        }
    }

    private static void staticMethod() {
        dummy++;
    }
}

随着Java 1.6.0_24 64-bithotSpot服务器在C2Q6600@3GHz上台,在进行第一次测量之后,这两种版本的时间稳定在266个ms(+/- 1 ms)。 当<代码>staticMethod()以人工编码时,时间也相同,预计从热电站开始。 删除<代码> dummy++ 当热点Spot优化其使用时,线将时间减少到零。

I also tested using Java 1.6.0_24 32-bit and with it the HotSpot Server VM had the same results, but the HotSpot Client VM had both versions producing results around 8660 ms (+/- 20 ms).

So we can conclude that the Server VM has better optimizations than the Client VM and that a try-catch which does nothing is either optimized away by HotSpot or that it does not affect the performance. To find which it is, print the assembly code produced by HotSpot.

Overall, measuring things which do nothing is pretty pointless.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签