静态块与静态方法 - 初始化静态字段 [英] Static block vs static method - initializing static fields
问题描述
出于好奇,我测量了静态块和静态方法初始化器之间的性能。首先,我在两个单独的java类中实现了上述方法,如下所示:
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, like so:
首先:
class Dummy {
static java.util.List<Integer> lista = new java.util.ArrayList<Integer>();
static {
for(int i=0; i < 1000000; ++i) {
lista.add(new Integer(i));
}
}
}
public class First {
public static void main(String[] args) {
long st = System.currentTimeMillis();
Dummy d = new Dummy();
long end = System.currentTimeMillis() - st;
System.out.println(end);
}
}
第二名:
class Muddy {
static java.util.List<Integer> lista = new java.util.ArrayList<Integer>();
public static void initList() {
for(int i=0; i < 1000000; ++i) {
lista.add(new Integer(i));
}
}
}
public class Second {
public static void main(String[] args) {
long st = System.currentTimeMillis();
Muddy.initList();
Muddy m = new Muddy();
long end = System.currentTimeMillis() - st;
System.out.println(end);
}
}
然后我执行这个小批量脚本测量它100次并将值放在一个文件中。 batchFile.bat First Second dum.res.txt
Then I executed this little batch script to measure it 100 times and put the values in a file. batchFile.bat First Second dum.res.txt
之后,我写了这段代码用来计算Dummy和Muddy测量值的平均值和标准差。
After that, I wrote this piece of code to calculate mean value and standard deviation of Dummy's and Muddy's measured values.
这是我得到的结果:
First size: 100 Second size: 100
First Sum: 132 Std. deviation: 13
Second Sum: 112 Std. deviation: 9
在我的其他机器上它也是类似的...每次我测试它。
And it is similar on my other machines...every time I test it.
现在我想知道,为什么会这样?我检查了字节码,Second.class在调用System.currentTimeMillis()之间有一条指令(调用静态initList())。
他们都做同样的事情,但为什么第一个更慢?我只能通过查看字节码来解释它,因为这是我第一次触摸 javap ;我还不懂字节码。
Now I'm wondering, why is it so? I checked the bytecode and Second.class has one instruction more (call to static initList()) between calls to System.currentTimeMillis(). They both do the same thing, but why is the First one slower? I can't really reason it out just by looking at the bytecode, since this was my first time touching javap; I don't understand bytecode yet.
推荐答案
我认为静态块版本比静态方法版本慢的原因可能是由于不同的JIT优化他们得到...
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 ...
有关更多有趣的信息,请参阅这篇有趣的文章: Java秘密:是否解释了静态块?
See this interesting article for more interesting information : Java Secret: Are static blocks interpreted?
这篇关于静态块与静态方法 - 初始化静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!