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
,说的就是这个事儿。
本文链接:https://cs.pynote.net/ag/202308021/
-- EOF --
-- MORE --