I was working on an array rotation algorithm, where you rotate an array left by d
steps of rotation.
I figured that slicing was a high level abstraction that would be much slower in reality than manually assigning each value in the array to a new location in the rotated array.
It turns out slicing is almost 40 times faster. Why is that?
Here is the code for comparison:
def rot_left_manual(a, d):
a_length = len(a)
rot_arr = [0] * a_length
for i in range(a_length):
rot_arr[(i-d) % a_length] = a[i]
return rot_arr
def rot_left_slice(a, d):
i = d % len(a)
b = a[i:]
b += (a[:i])
return b
I'm using %timeit
in Jupyter notebooks to time function speed