优化何时过早? [英] When is optimisation premature?

查看:108
本文介绍了优化何时过早?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如努斯所说,

我们应该忘记效率低下的问题,例如大约97%的时间:过早的优化是万恶之源.

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

这是Stack Overflow经常回答的问题,例如哪种是最有效的循环机制","SQL优化技术"? ().这些优化技巧的标准答案是分析您的代码,首先查看是否有问题,如果不是,那么就不需要您的新技术了.

This is something which often comes up in Stack Overflow answers to questions like "which is the most efficient loop mechanism", "SQL optimisation techniques?" (and so on). The standard answer to these optimisation-tips questions is to profile your code and see if it's a problem first, and if it's not, then therefore your new technique is unneeded.

我的问题是,如果特定技术不同但不是特别晦涩或模糊,那真的可以认为是过早的优化吗?

My question is, if a particular technique is different but not particularly obscure or obfuscated, can that really be considered a premature optimisation?

这是Randall Hyde的相关文章,名为 过早优化的谬论 .

Here's a related article by Randall Hyde called The Fallacy of Premature Optimization.

推荐答案

唐·努斯(Don Knuth)开始了 识字编程 运动,因为他认为计算机代码最重要的功能是将程序员的意图传达给人类读者.任何以性能为名使您的代码难以理解的编码实践都是过早的优化.

Don Knuth started the literate programming movement because he believed that the most important function of computer code is to communicate the programmer's intent to a human reader. Any coding practice that makes your code harder to understand in the name of performance is a premature optimization.

以优化的名义引入的某些习惯用法变得如此流行,以至于每个人都理解它们,并且它们已经成为期望,而不是过早的.例子包括

Certain idioms that were introduced in the name of optimization have become so popular that everyone understands them and they have become expected, not premature. Examples include

  • 在C语言中使用指针算术而不是数组表示法,包括使用以下惯用法

  • Using pointer arithmetic instead of array notation in C, including the use of such idioms as

for (p = q; p < lim; p++)

  • 在Lua中将全局变量重新绑定到局部变量,如

    local table, io, string, math
        = table, io, string, math
    

  • 除了这些惯用语之外,冒着危险也要走捷径.

    Beyond such idioms, take shortcuts at your peril.

    所有优化都为时过早,除非

    All optimization is premature unless

    • 程序太慢(很多人忘记了这一部分).

    • A program is too slow (many people forget this part).

    您有一个测量(配置文件或类似文件),它显示优化可以改善情况.

    You have a measurement (profile or similar) showing that the optimization could improve things.

    (也可以优化内存.)

    直接回答问题:

    • 如果您的不同"技术使程序难以理解,则这是过早的优化.

    编辑:为了回应评论,使用快速排序而不是诸如插入排序之类的更简单算法每个人都能理解和期望的习惯用法的另一个示例. (尽管如果您编写自己的排序例程而不是使用库排序例程,则希望您有一个非常很好的理由.)

    EDIT: In response to comments, using quicksort instead of a simpler algorithm like insertion sort is another example of an idiom that everyone understands and expects. (Although if you write your own sort routine instead of using the library sort routine, one hopes you have a very good reason.)

    这篇关于优化何时过早?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆