Premature Optimization is the root of all evil!

Last Updated: 2023-11-02 12:04:36 Thursday

-- TOC --

写代码时,常常遇到这样的场景:一个逻辑要顺畅的运行,要么在用逻辑自身处理特殊的或边界的情况(Special Case),或者直接单列出这些特殊情况,单独处理。用逻辑自身来处理特殊情况,代码更简洁优雅,相当于用一个招式“打遍天下”。但用逻辑自身处理特殊情况,性能较低,将特殊情况单列出来单独处理,这些特殊情况的处理性能就会很高。哪种方式更好呢?


Q: Sometimes, I'll try to code the special scenarios in algorithm to get accelerated speed. But by this way, normal scenario could be slow down a little. Is this a good programming practice?

A: A well known adage in computer science is “premature optimization is the root of all evil”. Basically, what this is trying to say is that working to make your code faster for special cases, before knowing whether those special cases will actual arise often (or at all), is a bad idea. If you’ve already finishing implementing your application, and are then able to test it on real world workloads, you should be able to identify appropriate targets for optimization (sometimes referred to as performance “bottlenecks”) and work on those. This is a good approach to take.

优化要寻找到bottlenecks,才能有的放矢!《COD》中排名第3的great idea,make common case fast,说的就是这个事儿。


-- EOF --

-- MORE --