What is the fastest way to expand the front of an array in python? Suppose I have 2 arrays: a and b. I want to make the fastest way a = b + a (b should not change).
My little benches:
test 1:
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
def f(a,b):
for i in range(0,100):
a=a+b
import cProfile
cProfile.run('f(a,b)')
time: ~ 12 s
test 2:
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
def f(a,b):
for i in range(0,100):
a[0:0] = b
import cProfile
cProfile.run('f(a,b)')
time: ~ 1.5 s
test3:
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
lenb = len(b)
def f(a,b):
for i in range(0,100):
b.extend(a)
b = b[:lenb]
import cProfile
cProfile.run('f(a,b)')
time: ~ 0.4 s
But I think it should be faster, because combining lists should be done as changing a few basic pointers. And the following code is the fastest, but b changes, and not (SO NOT GOOD FOR OUR PURPOSE): the "WRONG" test:
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
def f(a,b):
for i in range(0,100):
b.extend(a)
import cProfile
cProfile.run('f(a,b)')
time: ~ 0.13s
Thus, theoretically there should be a way to expand the front in time of the "WRONG" test.