Why code is slow.
WHAT TO DO FIRST
Measure.
Never optimise based on where you assume the time goes.
WHY
The assumption is usually wrong, and effort is spent in the wrong place.
HOW TO MEASURE
Time sections, or use a profiler reporting where time is spent.
WHAT USUALLY CAUSES SLOWNESS
Work repeated inside a loop that could be done once Repeated searching of a list File or network access inside a loop Loading everything into memory Queries issued per item rather than in one
THAT LAST ONE
The commonest cause in database-backed applications.
WHAT USUALLY DOES NOT MATTER
Micro-level differences between equivalent constructs.
WHAT TO CHANGE FIRST
The algorithm or the data structure.
A better structure beats any amount of tuning.
WHAT TO CONSIDER
Caching results that are expensive and repeated
WHAT TO BE CAREFUL WITH
Caching, which introduces staleness Optimising code that is not the bottleneck
WHAT TO MEASURE AFTERWARDS
Whether it actually improved.