Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localhostdotdev/bd97537dcbc4099bc05dd56bccd98cff to your computer and use it in GitHub Desktop.
Save localhostdotdev/bd97537dcbc4099bc05dd56bccd98cff to your computer and use it in GitHub Desktop.
performance of method_missing vs fetch vs [] vs Hash#[]
class U
def self.compare(reports, n: 10)
Benchmark.bm do |x|
reports.each do |report|
if report.is_a?(Proc)
x.report { n.times { report.call } }
else
x.report(report.first) { n.times { report.last.call } }
end
end
end
end
end
user = SimpleHash[a: 1]
user2 = { a: 1 }
U.compare(
[
['method_missing', -> { user.a }],
['fetch', -> { user.fetch(:a) }],
['[]', -> { user[:a] }],
['Hash#[]', -> { user2[:a] }]
], n: 1_000_000
)
# user system total real
# method_missing 1.397499 0.000694 1.398193 ( 1.398357)
# fetch 0.534996 0.000523 0.535519 ( 0.535599)
# [] 0.416706 0.000161 0.416867 ( 0.416923)
# Hash#[] 0.119884 0.000154 0.120038 ( 0.120084)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment