pythonでの文字の連結は、文字列よりリストを使おう!
先日のPython Code Reading 06で学んだこと。
pythonで文字を連結をする場合は、文字列のプラス('+')で連結するより
リストのappendを使った方が早いらしい。
で、試してみました。
下がソース
$ cat hoge.py #! /usr/bin/python import time class test1: def __init__(self, data): self.data = data def add_hoge(self): self.data = self.data + '_hoge' class test2: def __init__(self, data): self.data = [data] def add_hoge(self): self.data.append('_hoge') COUNT = 10000 for loop in xrange(0, COUNT, COUNT/10): print 'loop: %d' % loop t1 = test1('hoge') stime = time.time() for i in xrange(loop): t1.add_hoge() print 'test1 end time: %f' % (time.time() - stime) t2 = test2('hoge') stime = time.time() for i in xrange(loop): t2.add_hoge() print 'test2 end time: %f' % (time.time() - stime) print
で、下が結果
$ python hoge.py loop: 0 test1 end time: 0.000003 test2 end time: 0.000003 loop: 1000 test1 end time: 0.002336 test2 end time: 0.001719 loop: 2000 test1 end time: 0.003573 test2 end time: 0.002457 loop: 3000 test1 end time: 0.006850 test2 end time: 0.003388 loop: 4000 test1 end time: 0.052842 test2 end time: 0.005001 loop: 5000 test1 end time: 0.104933 test2 end time: 0.005615 loop: 6000 test1 end time: 0.172275 test2 end time: 0.007102 loop: 7000 test1 end time: 0.260971 test2 end time: 0.013219 loop: 8000 test1 end time: 0.363328 test2 end time: 0.011005 loop: 9000 test1 end time: 0.483130 test2 end time: 0.011366
test1が文字列で連結したもの。
test2がリストで連結したもの。
断然、リストで連結が早いっす!