Dicts 5x Faster than Sets

K

Kamilche

Hm, I just saw the 'sets' feature, and ran some timings to see if I
should use it instead of 'dict' sometimes. I discovered it's 4x slower
in adding, and 6x slower in removing items!

Here's the code, in case you're interested.

from sets import Set
import mytime

'''
Set Slower than Dict

Sample results:

Function Loops Seconds Loops/sec
***********************************************
Set add 1000000 1.391 718907
Set delete 1000000 1.14 877193
Dict add 1000000 0.344 2906975
Dict delete 1000000 0.172 5813955

'''

def test():
tmr = mytime.Timer()
max = 1000000
s = range(max)
print tmr.heading

s1 = Set()
tmr.startit()
for i in s:
s1.add(i)
tmr.stopit(max)
print tmr.results('Set add')
tmr.startit()
for i in s:
s1.remove(i)
tmr.stopit(max)
print tmr.results('Set delete')


tmr.startit()
s2 = {}
for i in s:
s2 = i
tmr.stopit(max)
print tmr.results('Dict add')
tmr.startit()
for i in s:
del s2
tmr.stopit(max)
print tmr.results('Dict delete')

test()
 
D

David Wilson

Hm, I just saw the 'sets' feature, and ran some timings to see if I
should use it instead of 'dict' sometimes. I discovered it's 4x slower
in adding, and 6x slower in removing items!

Which version of Python did you test this on? In the upcoming Python
2.4, sets will be significantly faster, so don't discard their use yet,
as they'll be implemented using native code within the year.


David.
 
A

Aahz

Hm, I just saw the 'sets' feature, and ran some timings to see if I
should use it instead of 'dict' sometimes. I discovered it's 4x slower
in adding, and 6x slower in removing items!

Speed is not the raison d'etre for sets, convenience and clarity are.
You are better off using sets if you need set intersection and union,
for example.

Keep in mind that dicts are probably the single most highly optimized
chunk of code in Python, and that sets are built on top of dicts.
Unless you need the absolute utmost in speed, the penalty you're paying
for the wrapper code shouldn't be an issue.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,838
Latest member
KandiceChi

Latest Threads

Top