代码大全学习-28-代码调整策略和技巧(Code-Tuning Stategies and Techniques)

    前面讲了重构,重构的目标是改善代码的可读性可维护性。这里讲的代码调整针对的主要目标是软件的性能。很多情况下,性能和可读性可维护性是相互矛盾的指标,所以在做代码调整之前,一定要想好它真的是需要的吗?提高软件的性能有很多种方法,列在下面的checklist中,代码调整是其他的方法都不行了才不得不用的方法。总之,慎用!
Checklist: Code-Tuning Strategies
 Overall Program Performance
  Have you considered improving performance by changing the program requirements?
  Have you considered improving performance by modifying the program's design?
  Have you considered improving performance by modifying the class design?
  Have you considered improving performance by avoiding operating system interactions?
  Have you considered improving performance by avoiding I/O?
  Have you considered improving performance by using a compiled language instead of an interpreted language?
  Have you considered improving performance by using compiler optimizations?
  Have you considered improving performance by switching to different hardware?
  Have you considered code tuning only as a last resort?
 Code-Tuning Approach
  Is your program fully correct before you begin code tuning?
  Have you measured performance bottlenecks before beginning code tuning?
  Have you measured the effect of each code-tuning change?
  Have you backed out the code-tuning changes that didn't produce the intended improvement?
  Have you tried more than one change to improve performance of each bottleneck, i.e., iterated?
    存在必有理由,既然总有些情形下我们不得不用代码调整,那么也要知道一下用的时候的一些技巧。首先要做的就是测量。性能好不好,速度有多快,光猜是不行的,必须要测量才知道;调整的效果怎么样,也只有测量了才知道。所以,测量是第一步。按照著名的80/20法则,总是有一小部分代码消耗了大部分性能,我们要通过测量找到那一小部分代码,然后对其进行调整优化。
    调整的方法就多种多样了,下面的checklist都列出来了,不一一详解,书中都有例子可以参考。要注意的就是不管哪个方法,因为编译器,所用的语言,环境不一样,其结果往往是不可预测的,所以代码调整的结果怎么样必须通过测量来确认。还值得一提的就是代码调整优化可以多管齐下,那样效果更佳。但同时也要注意,往往优化得越多,可读性可维护性越差,这需要权衡,做到什么程度算好。
Checklist: Code Tuning Techniques
 Improve Both Speed and Size
  Substitute table lookups for complicated logic
  Jam loops
  Use integer instead of floating-point variables
  Initialize data at compile time
  Use constants of the correct type
  Precompute results
  Eliminate common subexpressions
  Translate key routines to assembler
 Improve Speed Only
  Stop testing when you know the answer
  Order tests in case statements and if-then-else chains by frequency
  Compare performance of similar logic structures
  Use lazy evaluation
  Unswitch loops that contain if tests
  Unroll loops
  Minimize work performed inside loops
  Use sentinels in search loops
  Put the busiest loop on the inside of nested loops
  Reduce the strength of operations performed inside loops
  Change multiple-dimension arrays to a single dimension
  Minimize array references
  Augment data types with indexes
  Cache frequently used values
  Exploit algebraic identities
  Reduce strength in logical and mathematical expressions
  Be wary of system routines
  Rewrite routines in line
发布了63 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/tyst08/article/details/7983663