Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

performance

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, lines and total size, even if that means writing something like:

    //Code by: job
    //Topic: Code Golf - Collatz Conjecture
    n=input()
    while n>1:n=(n/2,n*3+1)[n%2];print n

So as a beginner I start to wonder whether size actually matters :D

It is obviously a very subjective question highly dependent on the actual code being used, but what is the rule of thumb in the real world.

In the case that size wont matter, how come then we don't focus more on performance rather than size?

like image 667
Carlos Avatar asked Mar 08 '10 06:03

Carlos


People also ask

Are shorter codes more efficient?

Arguably, using shorter lines of code is more efficient than spreading the code over several lines. If you have more lines of code, there are more places for bugs to hide and finding them might be more of a hassle. Fewer lines of code can achieve the same results (and probably better) than many lines of code.

What makes a code more efficient?

Using continue instead of break to skip over the rest of an iteration in a loop. Reuse variables when possible (e.g., don't create new ones every time) Use generators for large sequences or iterators that will be used multiple times; this saves memory because it only loads one element at a time.


1 Answers

I hope this does not become a flame war. Good code has many attributes, including:

  1. Solving the use-case properly.
  2. Readability.
  3. Maintainability.
  4. Performance.
  5. Testability.
  6. Low memory signature.
  7. Good user interface.
  8. Reusability.

The brevity of code is not that important in 21st century programming. It used to be more important when memory was really scarce. Please see this question, including my answer, for books referencing the attributes above.

like image 180
Yuval F Avatar answered Sep 19 '22 13:09

Yuval F