Skip to content

Instantly share code, notes, and snippets.

@finist
Created September 12, 2025 13:17
Show Gist options
  • Save finist/0e8e201eb7fc95acbc7d1c3de73f85cb to your computer and use it in GitHub Desktop.
Save finist/0e8e201eb7fc95acbc7d1c3de73f85cb to your computer and use it in GitHub Desktop.
Insertion into a linked list is 300 times slower than into an array.
class Node
attr_accessor :value, :next
def initialize(value)
@value = value
@next = nil
end
end
class LinkedList
attr_accessor :head
def initialize
@head = nil
end
def insert(value)
new_node = Node.new(value)
if @head.nil? || value < @head.value
new_node.next = @head
@head = new_node
return
end
current = @head
while current.next && current.next.value < value
current = current.next
end
new_node.next = current.next
current.next = new_node
end
end
require 'benchmark'
list = LinkedList.new
arr = []
n = 50_000
Benchmark.bm do |x|
x.report("LinkedList:") do
n.times { |i| list.insert("Item#{rand(1_000)}") }
end
x.report("Array:") do
n.times do |i|
value = "Item#{rand(1_000)}"
index = arr.bsearch_index { |x| x >= value } || arr.length
arr.insert(index, value)
end
end
end
@finist
Copy link
Author

finist commented Sep 12, 2025

Result:
user system total real
LinkedList: 29.945099 0.035970 29.981069 ( 29.981440)
Array: 0.130748 0.000875 0.131623 ( 0.131630)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment