Algorithms Dragon
Joined: 21 Oct 2004 Posts: 343 Location: Florida
|
Posted: Sun Sep 26, 2004 6:51 am Post subject: Python Quick Tips - append vs. += |
|
|
I am sure += works just fine for you and not only that it is easier to type than append() and it looks cleaner in those complex statements you have, right?
Well, what if I told you you can gain almost an entire usec per loop by not using += Now that would you say? What if I further told you that you can gain more than a an entire usec by making append a local?<br><br>Now are you still happy with your += See the results for yourself.
| Code: |
$ python /usr/lib/python2.3/timeit.py -n 1000000 -s's=[]' 's+=["foo"]'
1000000 loops, best of 3: 2.55 usec per loop
$ python /usr/lib/python2.3/timeit.py -n 1000000 -s's=[]' 's.append("foo")'
1000000 loops, best of 3: 1.66 usec per loop
$ python /usr/lib/python2.3/timeit.py -n 1000000 -s's=[]; a=s.append' 'a("foo")'
1000000 loops, best of 3: 1.2 usec per loop
|
The actual runtime results may vary depending on your system, but the performance gains will not. If you are running 2.4, you will see an ever greater margin of performance gain. |
|