-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
Closed
Labels
performancePerformance or resource usagePerformance or resource usagetype-featureA feature request or enhancementA feature request or enhancement
Description
Background
I noticed a difference in speed when inserting an element to the beginning of the list using list.insert vs list slice assignment. Upon inspecting the code, the usage of memmove
in the list slice assignment code seems to be the providing a slight speed boost over the for loop used in the list.insert implementation.
The following code was used to benchmark the difference:
import random
import timeit
runs = 100000
setup = 'import random;lst=[random.randrange(100000) for _ in range(100000)]; x = random.randrange(100000)'
print(timeit.timeit(stmt='lst[:0] = [x]', setup=setup, number=runs))
print(timeit.timeit(stmt='lst.insert(0, x)', setup=setup, number=runs))
Original:
Slice assignment: 7.394628149999335s
list.insert: 8.910868348000804s
Using memmove
in list.insert():
Slice assignment: 7.252985826999065s
list.insert: 7.215608489997976s
(Compiled with optimizations and tested on Arch Linux, kernel 5.18)
Metadata
Metadata
Assignees
Labels
performancePerformance or resource usagePerformance or resource usagetype-featureA feature request or enhancementA feature request or enhancement