什么时候优化还为时过早? [英] When is optimisation premature?

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

问题描述

正如 Knuth 所说,

As Knuth said,

我们应该忘记小效率,比如大约 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 的一篇相关文章,名为过早优化的谬误a>.

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

推荐答案

Don Knuth 开始了文学编程a> 运动,因为他相信计算机代码最重要的功能是将程序员的意图传达给人类读者.任何以性能为名使代码更难理解的编码实践都是过早的优化.

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 中使用指针算术代替数组符号,包括使用诸如

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

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

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

  • 除了这些习语之外,走捷径有风险.

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

    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天全站免登陆