Empty list as default parameter
Jay O'Connor
joconnor at nets.com
Sun Nov 23 21:25:26 EST 2003
Paul Rubin wrote:
>bokr at oz.net (Bengt Richter) writes:
>
>
>> changing the dynamic nature of the language.
>>
>>
>
>I think some of that dynamicness should be toned down as Python matures.
>
One aspect of Python's dynamic nature that has always intrigued me is in
the terms of how instance variables. Python allows you to dynamically
add instance variables as you need, which is pretty cool, but seems to
require a lookup of every instance variable reference, which can be
pretty slow.
Consider the following test case, using Python 2.3 on Win95 in IDLE:
=====================
class A:
def __init__(self, val=1):
self.value= val
def setval (self, v):
self.value=v
def getval (self):
return self.value
def test(self):
for x in range (1,1000000):
self.value = 1
y = self.value
import time
a = A()
print "start"
t1 = time.time()
a.test()
t2 = time.time()
print t2 - t1
print "done"
=====================
This routinely return values of over 6.3.
Swithing the implementation of test() to use the accessor methods kicked
the times up to over 20 seconds
By contrast the equvalent Smalltalk* code (VisualWorks 7,1) on the same
machine. gave me consistant results of a little over 600 milliseconds
when using direct variable access and roughly 1.5 seconds when using
accessors.
I think a portion of the difference in that in Smalltalk, instance
variables are specified in the class metadata (in terms of ordering)
when the class is compiled and thus an instance variable reference is
just a pointer offset from the start of the object data in memory and
thus the compiler can optimize instance variable reference by just
compiling in the offset into the the mehod code.
This is a case where Python is more dynamic than Smalltalk in that
Python allows easy addition of instance variables to objects, but it
comes at a price in terms of performance. The Smalltalk solution to
adding instance variables dynamically is just to carry around a
dictionary (similar to Python) but most experienced Smalltalkers know
that "instance variables are much faster than dictionary lookups so
consider if this is really the right design and consider the
performance/flexibility tradeoff"
This is one case where I think Python's flexibility hurts it in the long
run and perhaps as it goes forward, it will adapt to a more rigid style
that will provide for better performance without too much tradeoff.
After all, Python is still very young, Smalltalk has a twenty year head
start on it.
*Smalltalk code
======================
A>>#test
| y |
10000000 timesRepeat: [
self value: 1.
y := self value
]
-----------
| a |
a := A new.
Time millisecondsToRun: [a test].
======================
More information about the Python-list
mailing list