Static block vs static method - initializing static fields

后端 未结 2 1403
别跟我提以往
别跟我提以往 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.

提交回复
热议问题