Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic block vs static method - initializing static fields
    primarykey
    data
    text
    <p>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: </p> <p>First:</p> <pre><code>class Dummy { static java.util.List&lt;Integer&gt; lista = new java.util.ArrayList&lt;Integer&gt;(); static { for(int i=0; i &lt; 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); } } </code></pre> <p>Second:</p> <pre><code>class Muddy { static java.util.List&lt;Integer&gt; lista = new java.util.ArrayList&lt;Integer&gt;(); public static void initList() { for(int i=0; i &lt; 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); } } </code></pre> <p>Then I executed <a href="http://codepad.org/7plqLRVD" rel="nofollow">this</a> little batch script to measure it 100 times and put the values in a file. <code>batchFile.bat First Second dum.res.txt</code></p> <p>After that, I wrote <a href="http://codepad.org/YmME2Df4" rel="nofollow">this</a> piece of code to calculate mean value and standard deviation of Dummy's and Muddy's measured values. </p> <p>This is the result that I've got: </p> <pre><code>First size: 100 Second size: 100 First Sum: 132 Std. deviation: 13 Second Sum: 112 Std. deviation: 9 </code></pre> <p>And it is similar on my other machines...every time I test it.</p> <p>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 <em>javap</em>; I don't understand bytecode yet. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload