Created
March 17, 2012 03:46
-
-
Save Nimster/2054777 to your computer and use it in GitHub Desktop.
Important piece of functional programming and allocation of objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Often when doing functional style programming you get concerned that copying or | |
# wrapping objects might cost a lot in terms of performance. But the great thing | |
# about an immutable object is that I don't need to create a new one if I am | |
# handed an immutable copy. | |
# Follow me on twitter @nimrodpriell or see my blog at http://www.educated-guess.com | |
# for more bits of knowledge | |
# This is what we want to figure out the performance of. It is equivalent to calling | |
# frozenset(frozenset(frozenset(... m times (l)))...)) | |
def frozens(l,m=100): | |
for i in xrange(1,m): | |
if i % 2 == 0: # The if's and else's are here just to be as similar as possible to | |
# change() below | |
l = frozenset(l) | |
else: | |
l = frozenset(l) | |
# We compare this to what we would expect in a non-functional style. This is also a pitfall | |
# if you alternate the representation, you will hog your time for nothing. This is | |
# frozenset(list(frozenset(list( ... m times (list(l))))...)) | |
def change(l,m=100): | |
for i in xrange(1,m): | |
if i % 2 == 0: | |
l = list(l) | |
else: | |
l = frozenset(l) | |
# And just to rule out that list creation is what takes the time (although a (frozen)set has | |
# to hash everything... This is creating m frozen sets de-novo. | |
def allocates(l, m=100): | |
for i in xrange(1, m): | |
if i % 2 == 0: | |
frozenset(l) | |
else: | |
frozenset(l) | |
# The results: | |
# In [70]: time allocates(range(1,10000),10000) | |
# CPU times: user 3.17 s, sys: 0.01 s, total: 3.18 s | |
# Wall time: 3.18 s | |
# | |
# In [71]: time change(range(1,10000),10000) | |
# CPU times: user 2.12 s, sys: 0.01 s, total: 2.13 s | |
# Wall time: 2.13 s | |
# | |
# In [72]: time frozens(range(1,10000),10000) | |
# CPU times: user 0.01 s, sys: 0.00 s, total: 0.01 s | |
# Wall time: 0.01 s | |
# | |
# ... So don't worry. In this respect, functional programming has your back. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment