Time complexity of string slice

前端 未结 3 1019
粉色の甜心
粉色の甜心 2020-11-30 04:43

What\'s the time complexity of slicing a Python string? Given that Python strings are immutable, I can imagine slicing them being either O(1) or O(n)

3条回答
  •  执笔经年
    2020-11-30 05:21

    It all depends on how big your slices are. I threw together the following two benchmarks. The first slices the entire string and the second only a little bit. Curve fitting with this tool gives

    # s[1:-1]
    y = 0.09 x^2 + 10.66 x - 3.25
    
    # s[1:1000]
    y = -0.15 x + 17.13706461
    

    The first looks quite linear for slices of strings up to 4MB. I guess this really measures the time taken to construct a second string. The second is pretty constant, although it's so fast it's probably not that stable.

    import time
    
    def go(n):
        start = time.time()
        s = "abcd" * n
        for j in xrange(50000):
    
            #benchmark one
            a = s[1:-1]
    
            #benchmark two
            a = s[1:1000]
    
        end = time.time()
        return (end - start) * 1000
    
    for n in range(1000, 100000, 5000):
        print n/1000.0, go(n)
    

提交回复
热议问题