Returning Lists Of Instances Makes No Difference? And What About Performance?
Solution 1:
In principle, not returning anything is faster. In practice, it won't matter and is a useless micro-optimization.
Python does not move around objects, it moves references to objects (which are stored in names). If you have a C++ background, think of return a,b,c
giving back an array of three pointers. The performance overhead for this is negligible compared to all the other, explicit operations your function is doing.
If you are worried about performance, you should also not time your program. Either profile your program to find out where in your program considerable time is spent. Or time test code to find out how to do critical code (identified via profiling) better. A starting point are the timeit
package for timing code, and the various python profilers such as vmprof
.
For example, to find out the overhead of return
in general, you may time that explicit statement:
$ python3 -m timeit -s 'def foo():' -s ' pass''foo()'10000000 loops, best of 3: 0.0994 usec per loop
$ python3 -m timeit -s 'def foo():' -s ' return''foo()'10000000 loops, best of 3: 0.0981 usec per loop
$ python3 -m timeit -s 'def foo():' -s ' return 1, 2''foo()'10000000 loops, best of 3: 0.0961 usec per loop
$ python3 -m timeit -s 'bar, foo=object(), object()' -s 'def foo():' -s ' return foo, bar''foo()'10000000 loops, best of 3: 0.136 usec per loop
Whether your do not return, return nothing (an implicit None
) or return constants doesn't really matter. If you actually return objects, that adds about 0.04 usec (!!!) of overhead. Just calling a function is already is already 2.5 times as expensive for performance.
From a standpoint of coding style, IMO the view of python's standard library is best: if something is changed in-place, do not return it. This underlines that objects are changed via side-effects and there is no point to creating a new reference to them.
Post a Comment for "Returning Lists Of Instances Makes No Difference? And What About Performance?"