There are lots of principle
s and trick
s you can use to optimise your computer program
's performance (mostly time
, but sometimes memory space
). So many, in fact, that it's easy to forget the 2 cardinal rule
s of program optimisation
- Not now.
Don't optimise until you have to. Optimised code takes a lot longer to write, has more bugs, and is harder to maintain. Maybe your program will run fast enough, and you won't have to optimise?
Until you have a working program that runs too slowly, don't optimise it!
- Not here.
Almost all of a program's runtime is taken up by very few lines of code (the generally quoted rule is that 90% of the runtime is taken up by 10% of the code). Optimising anything else is most likely a waste of time.
So it's almost invariably true that you don't want to optimise any particular part of the program. Instead, profile your program, find the hotspots that make up the vast majority of the runtime, and optimise those.