[BangPypers] Tuples vs Lists, perfromance difference

Anand Chitipothu anandology at gmail.com
Thu Dec 24 12:22:13 CET 2009


On Thu, Dec 24, 2009 at 4:40 PM, Anand Chitipothu <anandology at gmail.com> wrote:
>> I didn't quite follow you here, I'm sorry.  I was chatting with someone in
>> IRC a week back, and here's his theory. He says in languages such as Python
>> or Perl, almost all I/O, database etc are all optimized in C and hence there
>> should not be much of a difference when it comes to such programs.
>>
>> By that theory anything which's in Python that's written in C such as
>> adding, multiplyiig should work as fast as C. However that's not the case
>> as mentioned here
>> http://wiki.python.org/moin/PythonSpeed/PerformanceTips#PythonisnotC
>
> C libraries are fast, python interpreter is not. If you are doing most
> of your work in a C library then your code will have comparable
> performance with C code. Thats why libraries like PIL, numpy as pretty
> fast.
>
> When you are doing multiplication in a loop, there is overhead for
> each python statement executed.
>
> A simple python statement "x = y + z" translates to something like this:
>
>    tmp1 = locals['y']
>    tmp2 = locals['z']
>    tmp3 = tmp1 + tmp2
>    locals['x'] = tmp3
>
> (this is pseudo code, not python)
>
> It has to look up y and z in locals dictionary, do the addition and
> put the result in locals dictionary back as x. The addition operation
> might be as fast as C, but there is a overhead of 2 dictionary lookups
> and one dictionary set.
>
> Jython compiler can compile Python code into Java. It will be
> worthwhile experience to experiment with it.

Here is more real example.

>>> def square(x): y = x*x; return y
...
>>> import dis
>>> dis.dis(square)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                0 (x)
              6 BINARY_MULTIPLY
              7 STORE_FAST               1 (y)
             10 LOAD_FAST                1 (y)
             13 RETURN_VALUE

As you see the interpreter is pretty stupid. It is loading x twice and
unnecessarily storing and loading y.

Anand


More information about the BangPypers mailing list