See the following code:
from timeit import timeit
import random
for size in (10 ** 3, 10 ** 4, 10 ** 5, 10 ** 6):
print('---')
nums = [random.randint(1, 10000000) for i in range(size)]
l = len(nums)
sp = l // 2
def with_slice():
for n in nums[sp:]:
pass
def pure_loop():
for i in range(sp, l):
pass
def no_slice():
for i in range(sp, l):
n = nums[i]
for method in (with_slice, pure_loop, no_slice):
print(f'Size={size:<10} method={method.__name__:<20} time={timeit(method, number=300)} ms')
The test results:
---
Size=1000 method=with_slice time=0.003086836077272892 ms
Size=1000 method=pure_loop time=0.00524100661277771 ms
Size=1000 method=no_slice time=0.01368624996393919 ms
---
Size=10000 method=with_slice time=0.031104332767426968 ms
Size=10000 method=pure_loop time=0.05062220152467489 ms
Size=10000 method=no_slice time=0.12812853325158358 ms
---
Size=100000 method=with_slice time=0.35493253357708454 ms
Size=100000 method=pure_loop time=0.5190340830013156 ms
Size=100000 method=no_slice time=1.2699861200526357 ms
---
Size=1000000 method=with_slice time=5.068190313875675 ms
Size=1000000 method=pure_loop time=5.029146575368941 ms
Size=1000000 method=no_slice time=12.877492633648217 ms
As far I as know, the slice operation will create a new list with the copy of the reference of the each item in the slice. In my imagination, it should be expensive than the no_slice way which doesn't have any copy operation. But from the test result, the slice way even is faster than the pure loop on a range(). Why does this happen?