Performance
suggest changeRuby is fast enough for most programs. When it isn't, the slowness is usually in a few hot spots: a lookup in a loop that should use a hash, a method that runs again and again with the same input, or work done when nobody needs the result. This article covers the techniques that give the biggest wins, roughly in the order you should try them:
- measure to find the hot spot
- turn on YJIT
- fix the algorithm and pick the right data structure
- do less work in hot loops
- use parallelism where it helps
All examples were run with Ruby 4.0. The timings come from one machine and will be different on yours. What matters is the ratio between the lines.
Measure first
Don't guess where the time goes. Profile the program with a sampling profiler such as stackprof or vernier (see Profiling), then compare alternatives with a benchmark (see Benchmarks).
The examples here use this small helper. It runs a block 5 times and prints the fastest run, because the minimum is the time least affected by GC pauses and other processes:
# bench.rb
require "benchmark"
# Run the block 5 times and print the fastest wall-clock time.
# The minimum is the least affected by GC pauses and other processes.
def bench(label)
best = 5.times.map { Benchmark.realtime { yield } }.min
printf("%-20s %8.1f ms\n", label, best * 1000)
end
The other scripts load it with require_relative "bench".
Turn on YJIT
YJIT is the just-in-time compiler built into CRuby. It compiles frequently executed Ruby methods to machine code. It's the cheapest speedup available, because you don't change any code:
# yjit.rb
require_relative "bench"
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
puts "YJIT enabled: #{defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?}"
bench("fib(32)") { fib(32) }
$ ruby yjit.rb
YJIT enabled: false
fib(32) 171.3 ms
$ ruby --yjit yjit.rb
YJIT enabled: true
fib(32) 23.2 ms
Method-call heavy code like this gains the most. Typical web applications get 15-30% faster.
There are three ways to turn it on:
- the
--yjitcommand-line flag, orRUBYOPT=--yjit - the
RUBY_YJIT_ENABLE=1environment variable, convenient for servers and containers RubyVM::YJIT.enableat runtime, for example after the application has booted, so that code that runs only once during startup isn't compiled:
# yjit_runtime.rb
require_relative "bench"
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
bench("interpreter") { fib(28) }
RubyVM::YJIT.enable
p RubyVM::YJIT.enabled?
bench("after enable") { fib(28) }
interpreter 26.0 ms
true
after enable 3.7 ms
Rails 7.2 and newer call RubyVM::YJIT.enable for you in an initializer when Ruby supports it.
Things to know about YJIT:
- Availability. YJIT is only present when Ruby was built with Rust available. Official Linux and macOS builds from version managers usually have it; check with
ruby -v(look for+YJIT) ordefined?(RubyVM::YJIT). The Windows RubyInstaller build doesn't include it, and--yjitthere only prints a warning. - Memory. Compiled code uses extra memory.
--yjit-mem-size=N(in MiB, default 128) caps the total YJIT memory. - Warm-up. A method is compiled only after it has been called a number of times, so benchmarks need a warm-up and short scripts may not benefit.
- Statistics.
--yjit-statsprints a detailed report on exit;RubyVM::YJIT.runtime_statsreturns some of it as a hash:
# ruby --yjit-stats=quiet stats.rb
def f(n) = n < 2 ? n : f(n - 1) + f(n - 2)
f(25)
p RubyVM::YJIT.runtime_stats.slice(:compiled_iseq_count, :inline_code_size, :yjit_alloc_size)
{compiled_iseq_count: 1, inline_code_size: 1114, yjit_alloc_size: 145338}
Ruby 4.0 also ships ZJIT, a new method-based JIT compiler enabled with --zjit. It's experimental; for production use YJIT.
Pick the right data structure
The biggest wins come from changing the complexity of an algorithm, not from tuning individual lines. A common case is Array#include? in a loop. It scans the array, so it's O(n). Set and Hash lookups are O(1):
# lookup.rb
require_relative "bench"
ids = Array.new(10_000) { |i| i * 7 }
set = ids.to_set # Set is built into Ruby 4.0, no require needed
hash = ids.to_h { |id| [id, true] }
probe = Array.new(1_000) { rand(70_000) }
bench("Array#include?") { probe.count { |x| ids.include?(x) } }
bench("Set#include?") { probe.count { |x| set.include?(x) } }
bench("Hash#key?") { probe.count { |x| hash.key?(x) } }
sorted = ids.sort
bench("bsearch") { probe.count { |x| sorted.bsearch { |y| y >= x } == x } }
Array#include? 24.6 ms
Set#include? 0.1 ms
Hash#key? 0.1 ms
bsearch 0.6 ms
If the data is already sorted, bsearch is O(log n) without building anything. See Sets for more on Set.
The same problem hides in "find the matching record" code. Here every order searches the whole user list:
# join.rb
require_relative "bench"
User = Struct.new(:id, :name)
Order = Struct.new(:id, :user_id, :total)
users = Array.new(2_000) { |i| User.new(i, "user#{i}") }
orders = Array.new(20_000) { |i| Order.new(i, rand(2_000), rand(100)) }
# O(users * orders): scans every user for every order
def names_slow(orders, users)
orders.map { |o| users.find { |u| u.id == o.user_id }.name }
end
# O(users + orders): build an index once, then look up in O(1)
def names_fast(orders, users)
by_id = users.to_h { |u| [u.id, u] }
orders.map { |o| by_id.fetch(o.user_id).name }
end
p names_slow(orders, users) == names_fast(orders, users)
bench("find in loop") { names_slow(orders, users) }
bench("hash index") { names_fast(orders, users) }
true
find in loop 957.0 ms
hash index 2.2 ms
That's over 400 times faster, and the gap grows with the data. group_by, index_by-style to_h, and tally are the usual tools for building such indexes in one pass.
Sorting and picking extremes
sort with a block calls the block O(n log n) times, and each call compares two values in Ruby. sort_by computes the key once per element and then sorts the keys in C. When you only need the largest or smallest few elements, don't sort at all:
# sorting.rb
require_relative "bench"
words = Array.new(100_000) { |i| "word#{rand(1_000_000)}" }
bench("sort with block") { words.sort { |a, b| a.size <=> b.size } }
bench("sort_by") { words.sort_by(&:size) }
bench("sort.last(5)") { words.sort.last(5) }
bench("max(5)") { words.max(5) }
bench("sort_by.first") { words.sort_by(&:size).first }
bench("min_by") { words.min_by(&:size) }
p words.max(5) == words.sort.last(5).reverse
sort with block 75.7 ms
sort_by 10.4 ms
sort.last(5) 36.0 ms
max(5) 2.0 ms
sort_by.first 12.4 ms
min_by 5.6 ms
true
max(n), min(n), max_by(n) and min_by(n) return the top n without sorting everything.
Stop as soon as you have the answer
Many Enumerable methods stop at the first match. Methods that build an array always process every element:
# early.rb
require_relative "bench"
nums = (1..1_000_000).to_a
bench("select.first") { nums.select { |n| n % 1000 == 0 }.first }
bench("find") { nums.find { |n| n % 1000 == 0 } }
bench("count > 0") { nums.count { |n| n > 10 } > 0 }
bench("any?") { nums.any? { |n| n > 10 } }
bench("map.select.first(3)") { nums.map { |n| n * n }.select(&:even?).first(3) }
bench("lazy...first(3)") { nums.lazy.map { |n| n * n }.select(&:even?).first(3) }
select.first 35.2 ms
find 0.0 ms
count > 0 30.3 ms
any? 0.0 ms
map.select.first(3) 99.6 ms
lazy...first(3) 0.0 ms
Use find, any?, all?, none? and include? instead of filtering and then checking. A lazy chain processes elements one at a time through all steps, so it can stop early. It has more overhead per element, so use it when you stop early or the input is huge (like lines of a big file), not as a general replacement for map.
Let built-in methods do the loop
Methods implemented in C run much faster than the same loop written in Ruby:
# builtin.rb
require_relative "bench"
nums = Array.new(1_000_000) { |i| i }
bench("while loop") do
total = 0
i = 0
while i < nums.size
total += nums[i]
i += 1
end
total
end
bench("each") { total = 0; nums.each { |n| total += n }; total }
bench("inject { }") { nums.inject { |a, b| a + b } }
bench("inject(:+)") { nums.inject(:+) }
bench("sum") { nums.sum }
while loop 19.4 ms
each 33.0 ms
inject { } 44.4 ms
inject(:+) 0.9 ms
sum 0.8 ms
sum is also more accurate for floats, because it uses Kahan-Babuska summation. Other examples: Array#pack and String#unpack1 for binary data, String#count, String#tr, Array#flatten, Hash#transform_values, each_slice, tally.
Do less work inside hot loops
Look for work that produces the same result on every iteration and move it out of the loop. For strings, prefer the simplest operation that does the job:
# strings.rb
require_relative "bench"
lines = Array.new(200_000) { |i| i.even? ? "ERROR disk full #{i}" : "INFO ok #{i}" }
bench("=~") { lines.count { |l| l =~ /\AERROR/ } }
bench("match?") { lines.count { |l| l.match?(/\AERROR/) } }
bench("start_with?") { lines.count { |l| l.start_with?("ERROR") } }
prefix = "error"
bench("interp regex") { lines.count { |l| l.match?(/\A#{prefix}/i) } }
re = /\A#{prefix}/i
bench("hoisted regex") { lines.count { |l| l.match?(re) } }
=~ 38.5 ms
match? 17.0 ms
start_with? 15.5 ms
interp regex 287.7 ms
hoisted regex 21.9 ms
=~creates aMatchDataobject and sets$~.match?only answers yes or no, so it allocates nothing.start_with?,end_with?andinclude?are faster than an equivalent regex.- A regex literal with
#{}is compiled again every time it's evaluated. Build it once outside the loop (or add theoflag,/#{prefix}/o, which interpolates only the first time, so it keeps the old pattern if the variable changes later).
Strings are also the most common source of unneeded allocations. Use << instead of += to build strings, add # frozen_string_literal: true, and prefer single-pass methods like filter_map and sum with a block over chains of map and select. Memory and garbage collection measures those allocations in detail.
Memoize expensive results
If a method is called repeatedly with the same inputs, cache the result. A Hash with a default block is a compact memoization table:
# memo.rb
require_relative "bench"
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
FIB = Hash.new { |h, n| h[n] = n < 2 ? n : h[n - 1] + h[n - 2] }
bench("plain fib(27)") { fib(27) }
bench("memo fib(27)") { FIB[27] }
p FIB[90]
plain fib(27) 13.4 ms
memo fib(27) 0.0 ms
2880067194370816120
For a value computed once per object, the usual idiom is @x ||= .... It has a trap: ||= recomputes when the cached value is nil or false. Use defined? to cache those too:
class Report
def initialize(rows) = @rows = rows
# ||= recomputes every time if the result is nil or false
def best
@best ||= begin
puts "computing best"
@rows.max
end
end
# defined? caches nil and false too
def missing
return @missing if defined?(@missing)
puts "computing missing"
@missing = @rows.find { |r| r > 100 }
end
end
r = Report.new([3, 9, 4])
2.times { r.best }
2.times { r.missing }
p r.best, r.missing
computing best
computing missing
9
nil
Caches that never shrink are a memory leak. If the set of keys is unbounded, limit the size or use a cache with eviction.
Method calls, blocks and dynamic dispatch
A method call in Ruby is cheap, but dynamic forms cost more:
# dispatch.rb
require_relative "bench"
class Point
attr_reader :x
def initialize(x) = @x = x
def get_x = @x
def method_missing(name, *args)
name == :ghost_x ? @x : super
end
def respond_to_missing?(name, include_private = false) = name == :ghost_x || super
end
pt = Point.new(1)
N = 1_000_000
bench("attr_reader") { N.times { pt.x } }
bench("def method") { N.times { pt.get_x } }
bench("send(:x)") { N.times { pt.send(:x) } }
bench("method_missing") { N.times { pt.ghost_x } }
def with_yield = yield
def with_block(&blk) = blk.call
bench("yield") { N.times { with_yield { 1 } } }
bench("&block.call") { N.times { with_block { 1 } } }
attr_reader 33.0 ms
def method 46.5 ms
send(:x) 77.1 ms
method_missing 232.4 ms
yield 69.6 ms
&block.call 102.6 ms
method_missingruns only after normal lookup fails, and then your code must check the name. If the set of names is known, generate real methods withdefine_methodonce instead.attr_readeris a bit faster than an equivalentdef.yielddoesn't need aProcobject. Capturing a block with&blkcreates one. Preferyieldunless you need to store the block or pass it on.
These are differences of tens of nanoseconds per call. They only matter in code that runs millions of times.
Records: Hash, Struct, Data or class
For a large number of small records, the kind of object matters:
# records.rb
require_relative "bench"
PointS = Struct.new(:x, :y)
PointD = Data.define(:x, :y)
class PointC
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
end
N = 300_000
bench("Hash") { N.times { |i| h = { x: i, y: i }; h[:x] + h[:y] } }
bench("Struct") { N.times { |i| s = PointS.new(i, i); s.x + s.y } }
bench("Data") { N.times { |i| d = PointD.new(x: i, y: i); d.x + d.y } }
bench("class") { N.times { |i| c = PointC.new(i, i); c.x + c.y } }
Hash 61.6 ms
Struct 59.5 ms
Data 151.1 ms
class 30.1 ms
A plain class with attr_reader is the fastest to create and read. Data is the slowest to create, because its constructor goes through keyword arguments. It's still a good choice for immutable values that aren't created in a tight loop.
For classes, set all instance variables in initialize, always in the same order. CRuby tracks the layout of each object as a "shape"; objects that gain instance variables in different orders get different shapes, which makes instance variable access slower and makes it harder for YJIT to optimize.
Concurrency and the GVL
CRuby has a Global VM Lock (GVL): only one thread runs Ruby code at a time. Threads still help when the program waits for I/O (network, disk, sleep), because the lock is released while waiting. For CPU-bound work, use Ractors or separate processes:
# parallel.rb
require_relative "bench"
def work(n) = (1..n).sum { |i| i * i % 7 }
N = 2_000_000
bench("serial x4") { 4.times.map { work(N) } }
bench("threads x4") { 4.times.map { Thread.new { work(N) } }.map(&:value) }
bench("ractors x4") { 4.times.map { Ractor.new { work(N) } }.map(&:value) }
bench("sleep serial") { 4.times { sleep 0.05 } }
bench("sleep threads") { 4.times.map { Thread.new { sleep 0.05 } }.each(&:join) }
parallel.rb:9: warning: Ractor API is experimental and may change in future versions of Ruby.
serial x4 301.6 ms
threads x4 447.8 ms
ractors x4 117.7 ms
sleep serial 200.6 ms
sleep threads 50.9 ms
Threads made CPU-bound work slower (lock contention) but cut the waiting time by 4x. Ractors run in parallel, but they're experimental and can only share immutable objects, so a lot of existing code and gems don't work inside them. The mature alternative for CPU-bound work is multiple processes: Process.fork on Unix-like systems, or a process-based server such as Puma in cluster mode. See Thread for more on threads.
I/O
Ruby's IO is buffered, so writing many small pieces to an open file is cheap. What's expensive is opening the file again and again, or forcing a flush after every write:
# io.rb
require_relative "bench"
require "tmpdir"
lines = Array.new(20_000) { |i| "line #{i}" }
path = File.join(Dir.tmpdir, "perf-io.txt")
bench("open per line") do
File.delete(path) if File.exist?(path)
lines.each { |l| File.open(path, "a") { |f| f.puts(l) } }
end
bench("sync = true") do
File.open(path, "w") { |f| f.sync = true; lines.each { |l| f.puts(l) } }
end
bench("one open") do
File.open(path, "w") { |f| lines.each { |l| f.puts(l) } }
end
bench("single write") { File.write(path, lines.join("\n") << "\n") }
p File.foreach(path).count
File.delete(path)
open per line 84.6 ms
sync = true 17.6 ms
one open 7.8 ms
single write 1.2 ms
20000
These numbers are from Linux. On Windows, where opening a file is much more expensive, "open per line" took 4.4 seconds. For reading, File.foreach processes a large file line by line without loading all of it into memory. See File I/O.
Startup time
For command-line tools, startup time can matter more than throughput. Most of it is loading RubyGems and the libraries you require:
# startup.rb
require_relative "bench"
require "rbconfig"
ruby = RbConfig.ruby
bench("ruby -e 1") { system(ruby, "-e", "1") }
bench("--disable-gems") { system(ruby, "--disable-gems", "-e", "1") }
bench("require 'json'") { system(ruby, "-e", "require 'json'") }
bench("require 'net/http'") { system(ruby, "-e", "require 'net/http'") }
ruby -e 1 64.9 ms
--disable-gems 9.7 ms
require 'json' 81.6 ms
require 'net/http' 141.9 ms
- Require libraries where they're needed, not all at the top, if most runs don't use them.
--disable-gemsis an option for scripts that use only the core library.- In large applications, the
bootsnapgem caches compiled code and load-path lookups and can cut boot time a lot (Rails includes it by default).
Checklist
- Profile before optimizing, and benchmark each change.
- Run production with YJIT.
- Replace linear searches in loops with a
HashorSetindex. - Use
sort_by,max(n),min_byinstead of sorting with a block or sorting everything. - Stop early with
find,any?andlazy. - Prefer built-in methods (
sum,tally,pack) over hand-written loops. - Move invariant work, especially regex construction, out of loops; use
match?andstart_with?. - Memoize repeated computations; watch out for
||=withnilandfalse. - Avoid
method_missingandsendin hot paths; preferyieldover&block. - Allocate less (see Memory and garbage collection).
- Use threads for I/O-bound work and processes or Ractors for CPU-bound work.
- Open files once and let
IObuffer writes.