From: "Strech (Sergey Fedorov) via ruby-core" Date: 2026-06-26T14:54:30+00:00 Subject: [ruby-core:125843] [Ruby Bug#22131] Avoid array allocation in `Array#include?` on literal arrays Issue #22131 has been updated by Strech (Sergey Fedorov). nobu (Nobuyoshi Nakada) wrote in #note-1: > Also `putnil` could be optimized. Yes, I thought about it, but decide to start small, I'm going to add it ---------------------------------------- Bug #22131: Avoid array allocation in `Array#include?` on literal arrays https://bugs.ruby-lang.org/issues/22131#change-117762 * Author: Strech (Sergey Fedorov) * Status: Open * ruby -v: ruby 4.1.0dev * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- I've noticed that `Array#include?` on a literal array of frozen-shareable elements (Integers, Symbols, true/false/nil, frozen String literals) compiles the receiver to `duparray`, which allocates a fresh `Array` copy on every call ��� even though `#include?` only reads it. **Before** ```ruby # frozen_string_literal: true [1, 2].include?(3) ``` ``` == disasm: #@-e:2 (2,0)-(2,18)> 0000 duparray [1, 2] ( 2)[Li] 0002 putobject 3 0004 opt_send_without_block 0006 leave ``` **After** ```ruby # frozen_string_literal: true [1, 2].include?(3) ``` ``` == disasm: #@-e:2 (2,0)-(2,18)> 0000 putobject 3 ( 2)[Li] 0002 opt_duparray_send [1, 2], :include?, 1 0006 leave ``` **Benchmarks** ```ruby require 'benchmark/ips' GC.disable ARR = [1, 2, 3] Benchmark.ips do |x| x.report "literal [1,2,3].include?(2)" do |loop| loop.times { [1, 2, 3].include?(2) } end x.report "constant ARR.include?(2)" do |loop| loop.times { ARR.include?(2) } end x.compare! end ``` | case | master | candidate | speedup | |---|---|---|---:| | `[1,2,3].include?(2)` | 17.83M i/s (56.09 ns) | 30.00M i/s (33.33 ns) | 1.68x | | `ARR.include?(2)` (const) | 23.92M i/s (41.80 ns) | 23.92M i/s (41.81 ns) | ~1.00x | Github PR: https://github.com/ruby/ruby/pull/17496 -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/