Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 134 ยท Testing and Tooling

Performance Tips

Practical Ruby performance - measure first, pick better algorithms and data structures, build strings efficiently, avoid extra allocations, use lazy enumerators, and understand what YJIT and ZJIT do.

Ruby is not the fastest language, but it is fast enough for an enormous number of programs, and it gets faster with every release. When a Ruby program is too slow, the cause is almost never "Ruby is slow". It is usually one of a small set of familiar reasons: the wrong algorithm, the wrong data structure, doing the same work repeatedly, creating far more objects than needed, or waiting for a database or network instead of computing. This lesson gives you a method for finding the real problem and a toolbox of fixes for the common ones.

One practical note first. Timings change on every run and every machine, so the examples on this page never print raw times. They print comparisons that hold by a wide margin (such as "the Set lookup finished faster than the Array search") or counts that never vary. In your own work you will print real numbers; see Benchmarking for the tools.

The golden rule: measure first

Programmers are bad at guessing where time goes. The loop you worry about may take one millisecond while an innocent-looking line takes a second. Follow this cycle:

  1. Decide that it is slow enough to matter. Code that runs once a day in 0.2 seconds is not a problem.
  2. Measure the whole operation, then find the hot spot with a profiler (a tool that samples where time is spent).
  3. Change one thing.
  4. Measure again and keep the change only if the number really improved.

Readable code that is fast enough beats clever code that is fast. Optimize the part that the numbers point at, and nothing else.

Below is a small helper we will reuse. It runs a block and returns the elapsed seconds on the monotonic clock.

Ruby A helper to compare two approaches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The honest result here is "it depends on the machine and Ruby build", which is exactly why you measure instead of assuming.

Choose the right algorithm and data structure

This is where almost all the big wins are. A better algorithm can make a program a thousand times faster; a micro-optimization usually saves a few percent. The most common mistake is searching a list over and over. Array#include? has to look at elements one by one (it is O(n)), while Hash and Set lookups jump straight to the answer in about constant time (O(1)).

Ruby Array search versus Set lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both versions give the same answer; the Set version just does not walk the list. If you see include? on a big array inside a loop, think Set or Hash. A second classic: nested loops that compare every item with every other (O(nยฒ)) can often become one pass that builds a hash index first.

Ruby From nested loops to a hash index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

With 3 users the difference is invisible. With 100,000 users and 1,000,000 orders the slow shape does about 100 billion comparisons and never finishes, while the fast one finishes almost at once. Learn the cost of the operations you use all the time: read about Arrays, Hashes and Sets.

A few more cheap algorithmic wins:

  • Do not repeat work. Compute a value once and reuse it (a local variable, or @value ||= expensive).
  • Memoize pure functions with a hash: Hash.new { |h, n| h[n] = ... }.
  • Sort once. sort_by with a cheap key beats sort with a slow comparison block, and min_by/max_by beat sorting just to take one end.
  • Use find instead of select.first: find stops at the first match, select scans everything and allocates an array.
  • Avoid reduce(:merge) or += on arrays in a loop: each step copies the whole accumulated structure, which makes the loop O(nยฒ). Mutate one accumulator with each_with_object, << or merge!.
Ruby Memoization with a Hash block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The plain version recomputes the same Fibonacci numbers again and again (21,891 calls for fib(20)); the memoized one computes each number exactly once (21 calls). A Hash with a default block is Ruby's one-line cache. See Recursion.

Strings: build once, copy less

Strings are mutable in Ruby, and every operation that returns a new string allocates a new object. In a loop this adds up. Compare the two ways to build a long string:

  • text += "x" creates a new string every time, copying the old contents. Over n iterations that copies O(nยฒ) characters.
  • text << "x" appends in place. It is the right tool inside a loop.
  • Collecting pieces in an array and calling join once is clear and fast, too.

We can count allocations with GC.stat, which does not depend on the machine's speed:

Ruby Counting allocations: += versus << versus join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

+= allocates a fresh result string on each pass (on top of the literal "x", which is also a new object each time unless the file freezes literals), while << keeps modifying one string. For templates with interpolation, "#{a} #{b}" is the fastest and clearest. Two more allocation savers:

  • Frozen string literals. With # frozen_string_literal: true, identical literals in a file can share one object, and a frozen constant like SEPARATOR = ", ".freeze is allocated once instead of every call. See Style and Linting and Frozen and immutable objects.
  • Symbols and Comparable/Struct/Data for identifiers and records; symbols are never duplicated.

Lazy enumerators: do only the work you need

Chains like map.select.first(3) on a big collection build a full intermediate array at every step. A lazy enumerator processes one element at a time through the whole chain and stops as soon as it has enough. This also lets you work with infinite sequences. See Enumerators.

Ruby Lazy versus eager chains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The eager chain squared all 1,000 numbers and tested all of them. The lazy chain stopped after the third match, which needed only 9 numbers. Laziness is not free (there is overhead per element), so it pays when the pipeline is long, the source is large or infinite, or you only need the first few results. For small arrays plain map is faster.

Fewer objects, less garbage

Ruby frees memory with a garbage collector (GC). Every object you create is eventually something the GC must look at, so creating fewer objects makes programs faster and more predictable. Look for:

  • Intermediate arrays. list.map(&:a).map(&:b) makes two arrays; one block that does both makes one. each_with_object, sum { } and count { } avoid temporary arrays that map.sum creates.
  • flat_map instead of map.flatten.
  • Reading huge files at once. File.read loads the whole file; File.foreach yields one line at a time (see Files and I/O).
  • Copies you do not need. Use <<, concat, merge! and map! when you own the object and nobody else holds it; keep the copying versions when sharing the data.
Ruby Counting objects in a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

What about YJIT and ZJIT?

Ruby can compile frequently used code to machine code while the program runs, instead of interpreting it each time. This is called JIT compilation (just-in-time). Ruby has two such compilers:

  • YJIT has been the production JIT since Ruby 3.1. It speeds up typical web applications noticeably (often 15 to 40 percent), at the cost of a bit more memory and a short warm-up.
  • ZJIT is the newer method-based JIT introduced in Ruby 4.0. It is still maturing and is aimed at long-term gains; check the release notes of your Ruby version before depending on it.

You switch them on with a flag or an environment variable. These commands are a read-only example, because the JIT is not enabled on our runner:

Terminal
# read-only example: shell commands, not run here
ruby --yjit app.rb
RUBYOPT="--yjit" bundle exec puma
ruby --zjit app.rb              # Ruby 4.0 and later
Ruby
# read-only example: asking a running program whether YJIT is on
puts RubyVM::YJIT.enabled?      # true when started with --yjit
RubyVM::YJIT.enable             # can also be switched on at runtime (Ruby 3.3+)

On this page's runner neither JIT is available, and the constant is not even defined, so a script must always guard such code:

Ruby Checking whether a JIT is available

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A JIT does not replace good algorithms. It makes the same algorithm run faster, by a constant factor; an O(nยฒ) program stays O(nยฒ).

Profiling: finding the real hot spot

When you do not know where the time goes, use a profiler. A sampling profiler looks at the call stack many times per second and counts which methods are on top; the methods seen most often are your hot spots. The common tools are third-party gems, so these are read-only examples:

Ruby
# read-only example: needs the stackprof gem
require "stackprof"

StackProf.run(mode: :cpu, out: "tmp/stackprof.dump", interval: 1000) do
  run_my_slow_code
end
# then: stackprof tmp/stackprof.dump --text --limit 10

Others to know: ruby-prof (call graphs), memory_profiler and derailed_benchmarks (memory and allocations), benchmark-ips (iterations per second with statistics), and rack-mini-profiler for Rails pages. For a quick look without any gem, a poor man's profiler is to time sections of the code with the seconds helper above and print how long each took.

Ruby A poor man's profiler: timing named sections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The include? inside the loop makes dedupe_slowly the slowest by far, which is the O(nยฒ) pattern again. Profilers find this kind of thing in real programs with thousands of methods.

When performance is not about Ruby

Slow Ruby programs are often slow because they wait. Look at these before rewriting any loop:

  • Database queries, especially "N+1" queries where you run one query per record in a list. Load related data in one query instead.
  • Network calls made one after another. Do them concurrently with threads (see Threads).
  • Output. Printing many small lines is slow; build the output and write it once.
  • Startup time. Loading large gems takes time; require only what you use.

Parallelism helps differently in Ruby. Threads share one Global VM Lock for Ruby code, so they speed up waiting (I/O) but not pure computation. For CPU-heavy work, look at processes or Ractors (see Ractors).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the first step when a Ruby program feels slow?

    You cannot reliably guess the bottleneck. Measure, change one thing, and measure again.
  2. 2. You call list.include?(x) inside a loop over 100,000 items, and list also has 100,000 items. What is the best improvement?

    Array#include? scans element by element, while Set lookups take roughly constant time, turning an O(nยฒ) program into O(n).
  3. 3. Why is s << "x" in a loop better than s += "x"?

    += builds a new string and copies the old contents on every pass, so it allocates and copies far more.
  4. 4. When does a lazy enumerator help most?

    Lazy chains handle one element at a time and can stop early, so they never build intermediate arrays or visit the rest of the source.
  5. 5. What does a JIT such as YJIT change?

    A JIT speeds up the interpreter by a constant factor; the algorithm's complexity and the GVL's limits stay the same.

Summary

  • Measure before optimizing: find the hot spot with a profiler or timers, change one thing, and measure again.
  • The biggest wins come from better algorithms and data structures: use Set and Hash for lookups, index data once, memoize, and avoid hidden O(nยฒ) patterns such as include? or += in loops.
  • Build strings with <<, join or interpolation, use frozen string literals, and avoid intermediate arrays (find over select.first, flat_map over map.flatten).
  • Lazy enumerators process one element at a time and stop early; they shine on large or infinite sources.
  • YJIT (and the newer ZJIT in Ruby 4.0) speeds up the interpreter by a constant factor; they do not fix a poor algorithm.
  • Many slow programs are waiting on a database, the network or I/O, not computing.

Next: Ruby Versions and Changes