Menu

#156 Strip redundant field initialisers

Some sunny day
accepted
None
6
2014-07-22
2014-07-21
No

The VM initialises fields to a default value if no initialiser for them is given. Numerical types are initialised to 0, object types to null.

Unfortunately, if you write code like:

private int someField = 0;

the compiler nevetheless generates an assignment "someField = 0" and sticks it in every constructor. Such assignments can safely be removed.

Discussion

  • Eric Lafortune

    Eric Lafortune - 2014-07-22

    Thanks for the suggestion. It's on my list as a nice addition, but these initializations can be surprisingly tricky to analyze, as shown by the recent bug report #531.

     
  • Eric Lafortune

    Eric Lafortune - 2014-07-22
    • status: open --> accepted
    • assigned_to: Eric Lafortune
    • Priority: 5 --> 6
     
  • Chris Kitching

    Chris Kitching - 2014-07-22

    It's certainly less trivial at the bytecode level than it is at source-level. I've recently been working on a source-level optimiser for Java, so had this down as a trivial problem.

    That said, it does seem that it'd be a fairly mundane dataflow analysis? For each field, scan each constructor and cull any assignment to the default value that isn't preceded in the graph by an assignment to a non-default value.

     
  • Eric Lafortune

    Eric Lafortune - 2014-07-22

    Consider the following scenario:

    1. The constructor of class A assigns null to its field F.
    2. However, the super constructor (in class B) is called before the constructor.
    3. This super constructor calls a public method M on itself.
    4. The public method M is overridden in class A and gets called instead.
    5. The public method M in class A assigns a non-null value to field F.

    The null assignment (in 1) then clears the assignment (in 5) and suddenly becomes essential. It's contrived, but possible.

    The same scenario could occur at the source level too.

     

Log in to post a comment.