Measure first, then optimize
The golden rule: never guess. Ruby's Benchmark measures what is actually slow – often it's not what you think. A classic: += on strings creates a new string every time, the shovel << extends the same one:
require "benchmark"
n = 5_000
plus = Benchmark.realtime do
s = ""
n.times { s += "x" }
end
shovel = Benchmark.realtime do
s = ""
n.times { s << "x" }
end
{ plus: plus.round(4), shovel: shovel.round(4) }Behind this sits the big topic of allocations: every unnecessary intermediate object costs time and memory. And the fastest optimization of all: code that never runs in the first place.
$ gem install benchmark-ips stackprof
# benchmark-ips: how many times per second? (more telling than one run)
# stackprof: WHERE does the program spend its time?Concurrency: with Thread, Ruby does several things “at once”. In MRI all threads share one interpreter (the GVL) – real gains therefore appear mostly while waiting (network, files); for CPU parallelism there are Ractors. The browser has no real threads, so Thread and sleep are simulated here (cooperatively, with virtual time) – but the API is the real one:
fetches = ["clients", "projects", "times"].map do |name|
Thread.new do
sleep 1 # simulated network download
"#{name}: loaded"
end
end
fetches.map(&:value)Three “downloads”, started with Thread.new, collected with value – on your machine this takes the time of one download instead of three. And because our simulated threads take turns at every sleep, you can even watch the interleaving in the output:
threads = 2.times.map do |i|
Thread.new do
3.times do |n|
puts "thread #{i}: step #{n}"
sleep 0.1
end
end
end
threads.each(&:join)
"done"By the way, under the hood of our simulation sit Fibers: cooperative mini-programs that pass control explicitly – the foundation of many async libraries. You can use them directly too:
narrator = Fiber.new do
Fiber.yield "Chapter 1: Bacon"
Fiber.yield "Chapter 2: More bacon"
"The end"
end
[narrator.resume, narrator.resume, narrator.resume]slow_report below scans the entries once per project – with many projects that turns quadratic. Write fast_report producing the same result with a single group_by pass. Measure the difference with Benchmark!entries = 500.times.map { |i| { project: "P#{i % 5}", hours: 1.0 } }
def slow_report(entries)
entries.map { |e| e[:project] }.uniq.to_h do |p|
[p, entries.select { |e| e[:project] == p }.sum { |e| e[:hours] }]
end
end
# def fast_report(entries)
# ...
# end
# require "benchmark"
# { slow: Benchmark.realtime { 50.times { slow_report(entries) } }.round(3),
# fast: Benchmark.realtime { 50.times { fast_report(entries) } }.round(3) }