Search code examples
javaperformancebytecode

Difference between two types of allocations


foo[] example = new foo[4];

variant 1

example [0] = example [1] = example [2] = example [3] = new foo(5);

variant 2

example [0] = new foo(5);
example [1] = example [0];
example [2] = example [0];
example [3] = example [0];

Is there a difference how Java handles both allocations internally? Have the first variant a special name? What is the difference in bytecode?


Solution

  • The first version is all one expression. The assignment expression causes the value to be stored into the array, and then the expression evaluates to the stored value. So it's all one giant expression and the same value is stored at each array position with no intervening reads.

    In the second version, it reads from the array each time. If you have multithreaded code and another thread is simultaneously modifying the array, then this could return different results.

    For single threaded code, they are effectively identical.

    Note: Here's what the first version looks like with parenthesis added to indicate order of evaluation.

    example [0] = (example [1] = (example [2] = (example [3] = (new foo(5)))));
    

    It is equivalent to the following code (note the lack of array reads)

    foo t = new foo(5);
    example[3] = t;
    example[2] = t;
    example[1] = t;
    example[0] = t;
    

    P.S. One other difference is that they assign the array elements in opposite order. So if the array has a length less than 4, the first version will throw immediately while the second version will partially fill the array.