IUnknown
IUnknown

Reputation: 9827

Method optimization

Which one would be faster and why?

public void increment{
  synchronized(this){
    i++;
  }
}

or

public synchronized void increment(){
  I++;
}

Would method inlining improve the second option?

Upvotes: 0

Views: 66

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533640

The difference is unlikely to matter or be visible but the second example could be faster. Why? In Oracle/OpenJDK, the less byte code a method uses the more it can be optimised e.g. inlined.

There is a number of thresholds for when a method could be optimised and these thresholds are based on the number of bytes of byte code. The second example uses less byte code so it is possible it could be optimise more.

One of these optimisations is escape analysis which could eliminate the use of synchronized for thread local object. This would make it much faster. The threshold for escape analysis is method which are under 150 bytes (after inlining) by default. You could see cases where the first solution makes the method just over 150 bytes and the second is just under 150 bytes.

NOTE:

  • don't write code on this basis, the different it too trivial to matter. Code clarity is far, far more important.
  • if performance does matter, using an alternative like AtomicInteger is likely to be an order of magnitude faster. (consistently, not just in rare cases)
  • BTW AFAIK the concurrency libraries use little assert statements, not because they are not optimised away but because they still count to the size of the byte code and indirectly slow down their use by meaning in some cases the code isn't as optimal. (this claim of mine should have a reference, but I couldn't find it)

Upvotes: 1

Related Questions