代码改变世界

Effective Java 55 Optimize judiciously

2014-04-18 22:46  小郝(Kaibo Hao)  阅读(414)  评论(0编辑  收藏  举报

Principle

  1. Strive to write good programs rather than fast ones.
  2. Strive to avoid design decisions that limit performance.

    Design components:

    1. APIs
    2. Wire-level protocols
    3. Persistent data formats
  3. Consider the performance consequences of your API design decisions.
    1. Make a public type mutable may require a lot of needless defensive coping(Item 39).
    2. Using inheritance in a public class where composition would have been appropriate ties the class forever to its superclass, which can place artificial limits on the performance of the subclass(Item 16).
    3. Using an implementation type rather than an interface in an API ties you to a specific implementation, even though faster implementations may be written in the future(Item 52).
  4. It is a very bad idea to warp an API to achieve good performance.  

Summary

Do not strive to write fast programs—strive to write good ones; speed will follow. Do think about performance issues while you're designing systems and especially while you're designing APIs, wire-level protocols, and persistent data formats. When you've finished building the system, measure its performance. If it's fast enough, you're done. If not, locate the source of the problems with the aid of a profiler, and go to work optimizing the relevant parts of the system. The first step is to examine your choice of algorithms: no amount of low level optimization can make up for a poor choice of algorithm. Repeat this process as necessary, measuring the performance after every change, until you're satisfied.