Created
April 20, 2019 17:20
-
-
Save localhostdotdev/bd97537dcbc4099bc05dd56bccd98cff to your computer and use it in GitHub Desktop.
performance of method_missing vs fetch vs [] vs Hash#[]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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