Skip to content

Instantly share code, notes, and snippets.

@amomchilov
Created December 13, 2023 15:07
Show Gist options
  • Select an option

  • Save amomchilov/d36ce98c8f84cc31d9e8bb39357db031 to your computer and use it in GitHub Desktop.

Select an option

Save amomchilov/d36ce98c8f84cc31d9e8bb39357db031 to your computer and use it in GitHub Desktop.
Object#equal? is faster than comparing object_ids
#!/usr/bin/ruby
# Warming up --------------------------------------
# a.equal?(b) 670.728k i/100ms
# a.id == b.id 367.019k i/100ms
# Calculating -------------------------------------
# a.equal?(b) 6.588M (± 2.5%) i/s - 33.536M in 5.093834s
# a.id == b.id 3.646M (± 3.0%) i/s - 18.351M in 5.038107s
#
# Comparison:
# a.equal?(b) : 6588048.0 i/s
# a.id == b.id: 3646134.0 i/s - 1.81x slower
require "benchmark/ips"
a = Object.new
b = Object.new
Benchmark.ips do |x|
x.report("a.equal?(b) ") do |times|
i = 0
while (i += 1) < times
Object.new.equal?(Object.new)
end
end
x.report("a.id == b.id") do |times|
i = 0
while (i += 1) < times
Object.new.object_id == Object.new.object_id
end
end
x.compare!
end
@amomchilov
Copy link
Copy Markdown
Author

BTW this measurement was in Ruby 3.2.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment