【问题标题】:Why does concatenation in Python appear to be getting slower?为什么 Python 中的连接似乎变慢了?
【发布时间】:2018-06-20 18:27:05
【问题描述】:

为什么在某些情况下 Python 3 中的连接比 Python 2 慢?

受影响最大的连接方法似乎是bytes 对象的连续连接,它的操作从 O(n) 变为 O(n²)。

我的大部分分析代码在这里:

#!/usr/bin/env python

from operator import concat
from sys import version, version_info
from timeit import timeit  # Compatibility: ver >= 2.6

# ver = version.partition('\n')[0].rstrip()
ver = '.'.join(str(v) for v in version_info[:3])
print(ver)

if version_info[0] == 2:
    from StringIO import StringIO
else:
    from io import StringIO
    from functools import reduce
    xrange = range


def build_plus():
    output = ''
    for _ in xrange(input_len):
        output += 'a'
    return output


def build_join():
    return ''.join('a' for _ in xrange(input_len))


def build_bytes_plus():
    output = b''
    for _ in xrange(input_len):
        output += b'a'
    return output


def build_stringio():
    output = StringIO()
    for _ in xrange(input_len):
        output.write('a')
    return output.getvalue()


def build_reduce():
    return reduce(concat, ('a' for _ in xrange(input_len)))


builds = {'str+': build_plus,
          'join': build_join,
          'reduce': build_reduce,
          'bytes+': build_bytes_plus,
          'StringIO': build_stringio}

if version_info[0] == 2:
    import cStringIO

    def build_cstringio():
        output = cStringIO.StringIO()
        for _ in xrange(input_len):
            output.write('a')
        return output.getvalue()

    builds['cStringIO'] = build_cstringio
else:
    from io import BytesIO

    def build_bytesio():
        output = BytesIO()
        for _ in xrange(input_len):
            output.write(b'a')
        return output.getvalue()

    builds['BytesIO'] = build_bytesio

resfile = open('times.csv', 'a')
size_range = 50  # Number of points over the size axis
min_order = 1.0  # 10^x byte input min
max_order = 5.0  # 10^x byte input max

for allow_gc in (False, True):
    setup = 'gc.enable()' if allow_gc else 'pass'

    for build_name, build_fun in builds.items():
        # For a roughly constant confidence interval, aim for uniform sample density across the
        # (logarithmic) input size axis.
        for size_index in range(size_range+1):
            input_len = int(10**((max_order-min_order)*size_index/size_range + min_order))

            # Rather than repeating many measurements at one input size, perform one measurement
            # per input size for a continuous range of input sizes and apply smoothing later.
            dur = timeit(build_fun, setup, number=1)

            resfile.write('"%s",%s,"%s",%d,%.6g\n' % (ver, str(allow_gc).upper(), build_name,
                                                      input_len, dur))

这里显示了我的 R 脚本中的一些图表:

【问题讨论】:

  • 是的,+ 循环中的字符串/字节对象应该具有二次行为。最近的版本尝试对此进行优化,但并不总是成功,并且是您应该避免的众所周知的反模式。使用 .join 注意,在 Python 2 中,bytes 只是 str 的别名
  • @juanpa.arrivillaga 很有趣。 Python 2 中的 strbytes 连接似乎都没有二次时间。
  • 因为在 Python 2 中 str is bytes。就像我说的,在 Python 3 中,这种优化保留给str,但显然没有打扰bytes。同样,这是一个众所周知的预期行为,更令人惊讶的是应该是优化的线性行为。只需使用加入。不要使用reduce(同样的问题)。请注意,sum 甚至会在您尝试将其与字符串 sum(['a','b','c'], '') 一起使用时引发错误。总的来说,好问题,顺便说一句

标签: python concatenation profiling


【解决方案1】:

在循环中将字符串与++= 连接从来都不是一个好主意。它看起来很有效,因为在字节码解释器循环中有一个weird, controversial special case,如果它可以证明没有其他人引用它正在弄乱的字符串,它将尝试可变地连接字符串。没有有效的调整大小政策;它只是 called realloc 并希望得到最好的结果,所以如果 realloc 需要复制,它仍然可能以 O(n^2) 结束。

在 Python 3 中,weird special case 现在处理 unicode 字符串而不是字节字符串。字节串连接每次都会回到构建一个新的字符串对象,所以你的循环会回到 O(n^2)。

【讨论】:

  • 很有趣。不过,为什么他们会放弃这种优化呢?这似乎是人们尝试的一件足够流行的事情(即使这是一个坏主意)。
  • @Reinderien 很好,他们为str 保留了它(相当于Python 2 unicode),这是常见的newby 用例。如果你在摆弄bytes,无论如何你应该知道得更好。
猜你喜欢
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 2014-06-23
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
相关资源
最近更新 更多