[Tutor] Performance of Python loops vs multiple MySQL queries

Alan Gauld alan.gauld at freenet.co.uk
Thu Dec 22 18:44:19 CET 2005


> Also there was a consideration of performance. I have one question on
> the topic breaking code into small functions and performance. I have
> read somewhere that *any* call whatoever, that is, methods, functions
> and such, involve a performance cost. Is that right?

Yes it is, but its not a huge cost. Unless you have a very time critical 
loop
calling lots of functions calling functions then don't worry unduly. And if
there is a problem use the profiler to tune the bits that need tuning.

The benefits of breaking code into functions in terms of readability and
maintenance far outweigh the performance hit in 99% of cases. Even in
the 1% its better to get it working slowly first then optimise later, 
exactly
where needed.

> proportional with the number of calls being made, so the larger the
> number of iterations and the more function calls, the slower the code
> would run, is that correct?

More or less, but a badly designed loop, or list comprehension will cancel
out any function call overhead very quickly. And disk reads or network
access will be order of magnitude slower still. Worrying about low level
performance tuning before you have a problem is usually a wasted effort.
High level performance tuning - getting the design clean - is another 
matter.
In all of the cases (bar one) where I've had major performamce issues to
fix they have been resolved at the architecture level (minimising network
or database accesses) not at the low level code.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list