Any way to refactor this?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed May 2 13:28:07 EDT 2007


On Wed, 02 May 2007 11:37:14 -0400, John Salerno wrote:

> Bruno Desthuilliers wrote:
> 
>>  From a purely efficiency POV, there are some obviously possible 
>> improvements. The first one is to alias visual.cylinder, so you save on 
>> lookup time. The other one is to avoid useless recomputation of 
>> -hatch_length and hatch_length*2.
>> 
>> def _create_3D_xhatches():
>>     cy = visual.cylinder
>>     for x in xrange(-axis_length, axis_length + 1):
>>         if x == 0: continue
>>         b = -hatch_length
>>         c = hatch_length*2
>>         cy(pos=(x, b, 0), axis=(0, c, 0), radius=hatch_radius)
>>         cy(pos=(x, 0, b), axis=(0, 0, c), radius=hatch_radius)
>>         cy(pos=(b, x, 0), axis=(c, 0, 0), radius=hatch_radius)
>>         cy(pos=(0, x, b), axis=(0, 0, c), radius=hatch_radius)
>>         cy(pos=(b, 0, x), axis=(c, 0, 0), radius=hatch_radius)
>>         cy(pos=(0, b, x), axis=(0, c, 0), radius=hatch_radius)
> 
> Doesn't this call to "cy" still call the function multiple times?

I'm not sure I understand what you mean, but here goes anyway...

Well, yes, but you have to call it six times per loop, with six different
sets of arguments, that's why there are six calls to it. I don't think
there's any way to reduce that (although if there is, the Original Poster
would probably love to hear about it).

Bruno's code has two micro-optimizations. The first is to avoid
looking up visual.cylinder each time (six times the number of loops) and
instead only look it up once. If axis_length is (say) 100, you save 1200
name look-ups of arbitrary complexity.

(Perhaps visual inherits from Klass, which inherits from Spam, which
inherits from Parrot, which inherits from Foo, which inherits from Bar,
which has a method "cylinder". Name look-ups can be time consuming.)

The second is to avoid calculating -hatch_length and hatch_length*2 for
each call, but to calculate them only once per loop. Again, only a
micro-optimization, but arithmetic in Python is more work than in (say) C,
because of the whole object oriented framework. So if you can avoid having
to look up hatch_length.__mul__ repeatedly, you may see a small but
significant time saving.


-- 
Steven.




More information about the Python-list mailing list