Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How expensive is to create a small list many times?

Tags:

python

I encounter the following small annoying dilemma over and over again in Python:

Option 1:

cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()

def do_something():    
  a_list = ["any", "think", "whatever"]    
  # read something from a_list

Option 2:

Uglier but more efficient (spare the a_list creation all over again)

a_list = ["any", "think", "whatever"]    
def do_something():    
  # read something from a_list

What do you think?

like image 451
GabiMe Avatar asked Mar 09 '10 13:03

GabiMe


2 Answers

What's ugly about it?

Are the contents of the list always constants, as in your example? If so: recent versions of Python (since 2.4) will optimise that by evaluating the constant expression and keeping the result but only if it's a tuple. So you could change it to being a tuple. Or you could stop worrying about small things like that.

Here's a list of constants and a tuple of constants:

>>> def afunc():
...    a = ['foo', 'bar', 'zot']
...    b = ('oof', 'rab', 'toz')
...    return
...
>>> import dis; dis.dis(afunc)
  2           0 LOAD_CONST               1 ('foo')
              3 LOAD_CONST               2 ('bar')
              6 LOAD_CONST               3 ('zot')
              9 BUILD_LIST               3
             12 STORE_FAST               0 (a)

  3          15 LOAD_CONST               7 (('oof', 'rab', 'toz'))
             18 STORE_FAST               1 (b)

  4          21 LOAD_CONST               0 (None)
             24 RETURN_VALUE
>>>
like image 55
John Machin Avatar answered Sep 28 '22 13:09

John Machin


Never create something more than once if you don't have to. This is a simply optimization that can be done on your part and I personally do not find the second example ugly at all.

Some may argue not to worry about optimizing little things like this but I feel that something this simple to fix should be done immediately. I would hate to see your application create multiple copies of anything that it doesn't need to simply to preserve an arbitrary sense of "code beauty". :)

like image 36
Andrew Hare Avatar answered Sep 28 '22 12:09

Andrew Hare