Writing shorter code/algorithms, is more efficient (performance)?

后端 未结 11 1813
半阙折子戏
半阙折子戏 2021-02-19 15:19

After coming across the code golf trivia around the site it is obvious people try to find ways to write code and algorithms as short as the possibly can in terms of characters,

11条回答
  •  鱼传尺愫
    2021-02-19 16:14

    There are many aspects to performance. Performance can for example be measured by memory footprint, speed of execution, bandwith consumption, framerate, maintainability, supportability and so on. Performance usually means spending as little as possible of the most scarce resource.

    When applied to networking, brevity IS performance. If your webserver serves a little javascript snippet on every page, it doesn't exactly hurt to keep the variable names short. Pull up www.google.com and view source!

    Some times DRY is not helping performance. An example is that Microsoft has found that they don't want a to loop through an array unless it is bigger than 3 elements. String.Format has signatures for one, two and three arguments, and then for array.

    There are many ways of trading one aspect for another. This is usually called caching.

    You can for example trade memory footprint for speed of execution. For example by doing lookup instead of execution. It is just a matter of replacing () with [] in most popular languages. If you plan it so that the spaceship in your game can only go in a fixed number of directions, you can save on trigonometric function calls.

    Or you can use a proxy server with a cache for looking up things over a network. DNS servers do this all the time.

    Finally, if development team availability is the most scarce resource, clarity of code is the best bet for maintainability performance, even if it doesn't run quite as fast or is quite as interesting or "elegant" in code.

提交回复
热议问题