python 字符串join_Python字符串连接与string.join有多慢?

我的原始代码是错误的,看来+的连接通常更快(尤其是在较新的硬件上使用较新版本的Python)

时间如下:

Iterations: 1,000,000

Windows 7,Core i7上的Python 3.3

String of len: 1 took: 0.5710 0.2880 seconds

String of len: 4 took: 0.9480 0.5830 seconds

String of len: 6 took: 1.2770 0.8130 seconds

String of len: 12 took: 2.0610 1.5930 seconds

String of len: 80 took: 10.5140 37.8590 seconds

String of len: 222 took: 27.3400 134.7440 seconds

String of len: 443 took: 52.9640 170.6440 seconds

Windows 7,Core i7上的Python 2.7

String of len: 1 took: 0.7190 0.4960 seconds

String of len: 4 took: 1.0660 0.6920 seconds

String of len: 6 took: 1.3300 0.8560 seconds

String of len: 12 took: 1.9980 1.5330 seconds

String of len: 80 took: 9.0520 25.7190 seconds

String of len: 222 took: 23.1620 71.3620 seconds

String of len: 443 took: 44.3620 117.1510 seconds

在Linux Mint,Python 2.7和较慢的处理器上

String of len: 1 took: 1.8840 1.2990 seconds

String of len: 4 took: 2.8394 1.9663 seconds

String of len: 6 took: 3.5177 2.4162 seconds

String of len: 12 took: 5.5456 4.1695 seconds

String of len: 80 took: 27.8813 19.2180 seconds

String of len: 222 took: 69.5679 55.7790 seconds

String of len: 443 took: 135.6101 153.8212 seconds

以下是代码:

from __future__ import print_function

import time

def strcat(string):

newstr = ''

for char in string:

newstr += char

return newstr

def listcat(string):

chars = []

for char in string:

chars.append(char)

return ''.join(chars)

def test(fn, times, *args):

start = time.time()

for x in range(times):

fn(*args)

return "{:>10.4f}".format(time.time() - start)

def testall():

strings = ['a', 'long', 'longer', 'a bit longer',

'''adjkrsn widn fskejwoskemwkoskdfisdfasdfjiz oijewf sdkjjka dsf sdk siasjk dfwijs''',

'''this is a really long string that's so long

it had to be triple quoted and contains lots of

superflous characters for kicks and gigles

@!#(*_#)(*$(*!#@&)(*E\xc4\x32\xff\x92\x23\xDF\xDFk^%#$!)%#^(*#''',

'''I needed another long string but this one won't have any new lines or crazy characters in it, I'm just going to type normal characters that I would usually write blah blah blah blah this is some more text hey cool what's crazy is that it looks that the str += is really close to the O(n^2) worst case performance, but it looks more like the other method increases in a perhaps linear scale? I don't know but I think this is enough text I hope.''']

for string in strings:

print("String of len:", len(string), "took:", test(listcat, 1000000, string), test(strcat, 1000000, string), "seconds")

testall()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值