Last active
May 26, 2024 12:49
-
-
Save pamelafox/2f884f2e2b7b3dd44a6212476180c87b to your computer and use it in GitHub Desktop.
War and Peace Insertion Showdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
class Link: | |
empty = () | |
def __init__(self, first, rest=empty): | |
self.first = first | |
self.rest = rest | |
def insert_at_start(self, value): | |
original_first = self.first | |
self.first = value | |
self.rest = Link(original_first, self.rest) | |
# From https://www.gutenberg.org/files/2600/2600-0.txt | |
filename = "warandpeace.txt" | |
big_file = open(filename, encoding="utf8") | |
big_str = big_file.read() | |
# Make a big python list | |
big_list = big_str.split(" ") | |
# Make a big linked list | |
big_ll = Link(big_list[0]) | |
word_num = 1 | |
current_link = big_ll | |
while word_num < len(big_list): | |
current_link.rest = Link(big_list[word_num]) | |
current_link = current_link.rest | |
word_num += 1 | |
# Time the Python list | |
time_taken = timeit.timeit(lambda: big_list.insert(0, "happy"), number=100000) | |
print(time_taken) | |
# Time the linked list | |
time_taken = timeit.timeit(lambda: big_ll.insert_at_start("happy"), number=100000) | |
print(time_taken) |
Thanks for sharing your timings! This was a classroom example for CS61A to motivate why linked lists might be desirable in some situations. I use lists for most of my production Python (or dicts/sets/etc as makes sense).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I feel that the claims of linked list superiority based on head-insert performance are dangerously misleading:
from https://gist.github.com/Iiridayn/f31e3b73983314d9d46e7cb7839aa2b1
Note that linked lists were only 4x faster when inserting at the head on my machine, and lists were superior in all other tests - overwhelmingly so with inserting at the midpoint or at the end.