When is optimisation premature?

前端 未结 20 1196
悲哀的现实
悲哀的现实 2020-11-21 23:26

As Knuth said,

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

20条回答
  •  温柔的废话
    2020-11-22 00:14

    Norman's answer is excellent. Somehow, you routinely do some "premature optimization" which are, actually, best practices, because doing otherwise is known to be totally inefficient.

    For example, to add to Norman's list:

    • Using StringBuilder concatenation in Java (or C#, etc.) instead of String + String (in a loop);
    • Avoiding to loop in C like: for (i = 0; i < strlen(str); i++) (because strlen here is a function call walking the string each time, called on each loop);
    • It seems in most JavaScript implementations, it is faster to do too for (i = 0 l = str.length; i < l; i++) and it is still readable, so OK.

    And so on. But such micro-optimizations should never come at the cost of readability of code.

提交回复
热议问题