how fast is object-oriented Python code?

B

beliavsky

I am reading about object-oriented programming in "Learning Python",
2nd. ed. by Lutz and Ascher. On p299, they write

"... most of the OOP story in Python boils down to the expression
object.attribute. [...] In fact, when classes are involved, the Python
expression above translates to the following in natural language:
'Find the first occurrence of attribute by looking in an object, and
all classes above it, from bottom to top and left to right'"

It seems to me that doing this in a scripting language, at run-time,
could be slow, compared to an equivalent code not using classes. How
fast is Python OO code compared to non-OO code?

I know that object-oriented numerical code in C++ can be much slower
than the procedural C or Fortran equivalent, unless one is careful. To
what extent is this true with OO and non-OO Python?
 
P

Peter Otten

I know that object-oriented numerical code in C++ can be much slower
than the procedural C or Fortran equivalent, unless one is careful. To
what extent is this true with OO and non-OO Python?

$ timeit.py -s"def x(): pass" "x()"
1000000 loops, best of 3: 0.437 usec per loop
$ timeit.py -s"class X:" -s" def x(self): pass" -s"x=X()" "x.x()"
1000000 loops, best of 3: 0.694 usec per loop

The above bogus example would suggest an extra cost of 60 percent.
Let's modify it a little:

$ timeit.py -s"class X:" -s" def x(self): pass" -s"x=X().x" "x()"
1000000 loops, best of 3: 0.446 usec per loop

With a tiny change almost all of the overhead goes away. I think with a
grain of salt the same is true on a larger scale. The speed of an
application is determined by the quality of its design, not by the
programming paradigm employed.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top