Created
August 4, 2012 17:15
-
-
Save djfroofy/3258823 to your computer and use it in GitHub Desktop.
Lists vs. StringIO vs. Regular String Concat for building strings in Python
This file contains 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
IPython 0.10.1 -- An enhanced Interactive Python. | |
? -> Introduction and overview of IPython's features. | |
%quickref -> Quick reference. | |
help -> Python's own help system. | |
object? -> Details about 'object'. ?object also works, ?? prints more. | |
In [2]: from string_building_perf import * | |
In [3]: %timeit build_ul_list(100000) | |
10 loops, best of 3: 77.9 ms per loop | |
In [4]: %timeit build_ul_stringio(100000) | |
10 loops, best of 3: 109 ms per loop | |
In [5]: %timeit build_ul_concat(100000) | |
10 loops, best of 3: 66.1 ms per loop | |
In [6]: %timeit build_ul_list(100000, get_random_word) | |
1 loops, best of 3: 245 ms per loop | |
In [7]: %timeit build_ul_stringio(100000, get_random_word) | |
1 loops, best of 3: 269 ms per loop | |
In [8]: %timeit build_ul_concat(100000, get_random_word) | |
1 loops, best of 3: 203 ms per loop |
This file contains 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
from cStringIO import StringIO | |
from itertools import permutations | |
import string | |
import random | |
word = 'x' * 8 | |
words = [''.join(p) for p in permutations(string.letters[:8])] | |
def get_8x(): | |
return word | |
def get_random_word(): | |
return random.choice(words) | |
def build_ul_list(linect, get_word=get_8x): | |
buffer = ['<ul>\n'] | |
for i in xrange(linect): | |
buffer.append('<li>%s</li>\n' % get_word()) | |
buffer.append('</ul>') | |
return ''.join(buffer) | |
def build_ul_stringio(linect, get_word=get_8x): | |
buffer = StringIO() | |
buffer.write('<ul>\n') | |
for i in xrange(linect): | |
buffer.write('<li>%s</li>\n' % get_word()) | |
buffer.write('</ul>') | |
return buffer.getvalue() | |
def build_ul_concat(linect, get_word=get_8x): | |
buffer = '<ul>\n' | |
for i in xrange(linect): | |
buffer += ('<li>%s</li>\n' % get_word()) | |
buffer += '</ul>' | |
return buffer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment