Static block vs static method - initializing static fields

后端 未结 2 1377
别跟我提以往
别跟我提以往 2021-02-06 05:58

Out of curiosity, I measured the performance between static block and static method initializer. First, I implemented the above mentioned methods in two separate java classes, l

相关标签:
2条回答
  • 2021-02-06 06:06

    Here's my guess as to the reason for this:

    The initialization you are doing is creating enough objects that it is causing one or more garbage collections.

    When the initialization is called from the static block, it is done during the class initialization rather than during simple method execution. During class initialization, the garbage detector may have a little more work to do (because the execution stack is longer, for example) than during simple method execution, even though the contents of the heap are almost the same.

    To test this, you could try adding -Xms200m or something to your java commands; this should eliminate the need to garbage collect during the initialization you are doing.

    0 讨论(0)
  • 2021-02-06 06:18

    I think that the reason why the static block version is slower than the static method version could be due to the different JIT optimization that they get ...

    See this interesting article for more interesting information : Java Secret: Are static blocks interpreted?

    0 讨论(0)
提交回复
热议问题