Rails enum methods get up to 5x faster by generating real code instead of public_send

Rails Is a JIT Compiler

Rails enum methods get up to 5x faster by generating real code instead of public_send

A Rails performance team member was skeptical when asked whether inlining enum methods in an external build step would help. The real culprit was Rails' own enum implementation: it used define_method with a captured block and public_send, even though the method name and value are known at definition time. Switching to module_eval with generated code pushed a microbenchmark from 3.8M to 18.5M iterations per second under ZJIT. Edge cases included odd enum names and non-finite floats.

There is no reason to be using public_send for method dispatch if you know the name statically: it doesn't get cached and has a lot more machinery than we need.
  1. matltc

    If you found this interesting, and especially if you write Ruby, I cannot recommend Metaprogramming Ruby highly enough. Fundamentally changed the way I think about programming, and opened my mind to what is possible when one frees themselves from dogmatic, generic best practices. It covers these topics in great detail, and uses examples from ActiveRecord and many other gems' implementations of them.

  2. twiss

    class Order < ActiveRecord::Base

    enum :status, { pending: 0, paid: 1, shipped: 2, refunded: 3 }

    def shippable?

    paid? && !refunded?

    end

    end

    Bit off-topic but if `:status` is an enum, then `paid? && !refunded?` is equivalent to `paid?`

  3. WesolyKubeczek

    Opens the article

    > The title was bait to get you to open this article. But

    Closes the article

More from this day

2026-10-24