java compiler optimization

前端 未结 5 1347
北荒
北荒 2020-12-11 11:10

Is the Java compiler smart enough to optimize loop below, by extracting the

Double average = new Double( totalTime / callCount ); 

out of t

5条回答
  •  难免孤独
    2020-12-11 11:38

    This may seem like an obvious optimization at first, but I don't think so, since it involves object instantiation. Granted, it's an instantiation of an immutable primitive box type, but that still doesn't guarantee that there's no side effect.

    I don't think any current compiler can optimize this. For this to be optimized, the compiler must be told that some classes have special properties (which can be a dangerous proposition given that things may change in the future). That is, the compiler must be told specifics of the API. This can not be optimized at the language-level alone.

    If you use double, however, it's much more likely to be optimized (e.g. using the loop-invariant code motion technique).

提交回复
热议问题