Functions vs Methods
Hi It is said that function calls are expensive. Does that mean one must use available methods instead? Eg. x is a NumPy array, and I need its transpose Should I use
x.T
or
numpy.transpose(T) ?
Does it matter which one I'm using ? If not, under what conditions does it become important to think about this distinction? Thanks
Hi Jaidev, On Wed, Dec 28, 2011 at 12:09:45PM +0530, Jaidev Deshpande wrote:
Eg. x is a NumPy array, and I need its transpose
Should I use
x.T
or
numpy.transpose(T) ?
If you are wondering for a timing reason, use IPython's '%timeit' magic to figure out if it does make a difference or not. In general, I tend to prefer 'x.T', which I find more readable. Gael
On Wed, Dec 28, 2011 at 06:39, Jaidev Deshpande <deshpande.jaidev@gmail.com> wrote:
Hi
It is said that function calls are expensive. Does that mean one must use available methods instead?
For the most part, it usually doesn't matter enough to care about. Whether you use the methods or the functions should be dominated by other concerns like readability and genericity. Typically, this means that you do want the methods, but not for performance reasons. Note that when we say "function calls are expensive", we mean that the call overhead for functions and methods implemented in pure Python is expensive relative to functions and methods implemented via C. By "overhead", we mean the extra time that isn't related to the actual computation itself, like setting up the stack frame, packing and unpacking the arguments, etc. Extension functions/methods don't need to do as much of this. Really, the performance difference only matters when you have thousands of calls in a tight loop, at which point you should be thinking about reorganizing your algorithm anyways. This is a micro-optimization. Micro-optimizations have their place: namely, after you have done all of the macro-optimizations that you can. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco
participants (3)
-
Gael Varoquaux -
Jaidev Deshpande -
Robert Kern