开发人员应该首先考虑可读性还是性能? [英] Should a developer aim for readability or performance first?

查看:49
本文介绍了开发人员应该首先考虑可读性还是性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发人员通常会面临两种解决问题的可能方法之间的选择——一种是惯用且可读的,另一种是不太直观但可能执行得更好.例如,在基于 C 的语言中,有两种方法可以将数字乘以 2:

Oftentimes a developer will be faced with a choice between two possible ways to solve a problem -- one that is idiomatic and readable, and another that is less intuitive, but may perform better. For example, in C-based languages, there are two ways to multiply a number by 2:

int SimpleMultiplyBy2(int x)
{
    return x * 2; 
}

int FastMultiplyBy2(int x)
{
    return x << 1;
}

对于技术和非技术读者来说,第一个版本更容易上手,但第二个版本可能表现更好,因为位移是比乘法更简单的操作.(现在,我们假设编译器的优化器不会检测到并优化它,尽管这也是一个考虑因素).

The first version is simpler to pick up for both technical and non-technical readers, but the second one may perform better, since bit shifting is a simpler operation than multiplication. (For now, let's assume that the compiler's optimizer would not detect this and optimize it, though that is also a consideration).

作为开发者,初次尝试哪个更好?

As a developer, which would be better as an initial attempt?

推荐答案

你错过了一个.

首先编码是为了正确性,然后是为了清晰(当然,这两者通常是联系在一起的!).最后,只有当你有真正需要的真实经验证据时,你才能考虑优化.过早的优化确实是邪恶的.优化几乎总是花费您的时间、清晰度和可维护性.你最好确保你买的是值得的东西.

First code for correctness, then for clarity (the two are often connected, of course!). Finally, and only if you have real empirical evidence that you actually need to, you can look at optimizing. Premature optimization really is evil. Optimization almost always costs you time, clarity, maintainability. You'd better be sure you're buying something worthwhile with that.

请注意,好的算法几乎总是胜过局部调整.您没有理由不能拥有正确、清晰和快速的代码.不过,从专注于快速"开始,你会非常幸运地到达那里.

Note that good algorithms almost always beat localized tuning. There is no reason you can't have code that is correct, clear, and fast. You'll be unreasonably lucky to get there starting off focusing on `fast' though.

这篇关于开发人员应该首先考虑可读性还是性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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