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?
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.
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.
I hope this does not become a flame war. Good code has many attributes, including:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With