Forked from justinvanwinkle/python string concat test
Created
February 7, 2010 09:16
-
-
Save mahmoudimus/297339 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from cStringIO import StringIO | |
from UserString import MutableString | |
data = xrange(100000) | |
def test_naive_way(): | |
accum = '' | |
for x in data: | |
accum += str(x) | |
return accum | |
def test_join_way(): | |
return ''.join([str(x) for x in data]) | |
def test_generator_join_way(): | |
return ''.join((str(x) for x in data)) | |
def test_join_for_way(): | |
accum = [] | |
for x in data: | |
accum.append(str(x)) | |
return ''.join(accum) | |
def _test_mutable_way(): | |
accum = MutableString() | |
for x in data: | |
accum += str(x) | |
return accum | |
def test_stringio_way(): | |
f = StringIO() | |
for x in data: | |
f.write(str(x)) | |
return f.getvalue() | |
if __name__ == '__main__': | |
from timeit import Timer | |
itercnt = 1000 | |
expression = "%s()" | |
impst = "from __main__ import %s, StringIO, data, MutableString" | |
funcs = [x for x in globals().keys() if x.startswith('test_')] | |
for f in funcs: | |
t = Timer(expression % f, impst % f) | |
print f, t.timeit(itercnt) | |
""" | |
% python stringcat.py | |
test_join_for_way 47.743074894 | |
test_generator_join_way 42.0865740776 | |
test_naive_way 36.9351909161 | |
test_join_way 40.2822668552 | |
test_stringio_way 50.0085318089 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment