Tuesday, October 14, 2014

NetBeans 8.0's Five New Performance Hints

NetBeans 8.0 introduces several new Java hints. Although there are a large number of these new hints related to Java Persistence API, I focus on five new hints in the Performance category.

The five new "Performance Hints" introduced with NetBeans 8.0 are:

  • Boxing of already boxed value
  • Redundant String.toString()
  • Replace StringBuffer/StringBuilder by String
  • Unnecessary temporary during conversion from String
  • Unnecessary temporary during conversion to String

Each of these five performance-related Java hints are illustrated in this post with screen snapshots taken from NetBeans 8.0 with code that demonstrates these hints. There are two screen snapshots for each hint, one each showing the text displayed when the cursor hovers over the line of code marked with yellow underlining and one each showing the suggested course of action to be applied to address that hint (shown when clicking on the yellow light bulb to the left of the flagged line). Some of the captured screen snapshots include examples of code that avoid the hint.

Boxing of Already Boxed Value

Redundant String.toString()

Replace StringBuffer/StringBuilder by String

Unnecessary Temporary During Conversion from String

Unnecessary Temporary During Conversion to String

Unless I've done something incorrectly, there appears to be a minor bug with this hint in that it reports "Unnecessary temporary when converting from String" when, in this case, it should really be "Unnecessary temporary when converting to String". This is not a big deal as the condition is flagged and the action to fix it seems appropriate.

Conclusion

The five performance-related hints introduced by NetBeans 8.0 and illustrated here can help Java developers avoid unnecessary object instantiations and other unnecessary runtime cost. Although the benefit of this optimization as shown in my simple examples is almost negligible, it could lead to much greater savings when used in code with loops that perform these same unnecessary instantiations thousands of times. Even without consideration of the performance benefit, these hints help to remind Java developers and teach developers new to Java about the most appropriate mechanisms for acquiring instances and primitive values.

No comments: