Skip to content

Instantly share code, notes, and snippets.

@britishtea
Last active January 27, 2021 18:37
Show Gist options
  • Save britishtea/69f4e1a4524ef2dfefc3 to your computer and use it in GitHub Desktop.
Save britishtea/69f4e1a4524ef2dfefc3 to your computer and use it in GitHub Desktop.
Array#join vs Regexp.union (ran on Ruby 2.0.0)
require "benchmark/ips"
input = %w[one two three four five six seven]
Benchmark.ips do |x|
x.report "Array#join" do
Regexp.new input.map { |e| Regexp.escape e }.join "|"
end
x.report "Regexp.union" do
Regexp.union input
end
x.compare!
end
$ ruby -v
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin13]
$ ruby benchmark.rb
Calculating -------------------------------------
Array#join 4044 i/100ms
Regexp.union 3947 i/100ms
-------------------------------------------------
Array#join 46052.1 (±3.6%) i/s - 230508 in 5.012008s
Regexp.union 43411.7 (±4.0%) i/s - 217085 in 5.009206s
Comparison:
Array#join: 46052.1 i/s
Regexp.union: 43411.7 i/s - 1.06x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment