-
-
Save dineshpanda/e912392c72c62c7f85ca14207be37c7b to your computer and use it in GitHub Desktop.
This file contains 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
require 'active_support/inflector' | |
require 'benchmark' | |
class James | |
end | |
class John | |
end | |
class Jimmy | |
end | |
NAMES = %w(James Jimmy John).freeze | |
CLASSES = [James, John, Jimmy].freeze | |
NAME_HASH = { | |
:James => James, | |
:John => John, | |
:Jimmy => Jimmy | |
}.freeze | |
def find_by_case(str) | |
case str | |
when 'James' then James | |
when 'John' then John | |
when 'Jimmy' then Jimmy | |
end | |
end | |
def find_by_array(str) | |
CLASSES[NAMES.find_index(str)] | |
end | |
def find_by_hash(str) | |
NAME_HASH[str.to_sym] | |
end | |
def find_by_const_get(str) | |
Kernel.const_get(str) | |
end | |
names = %w(James Jimmy John) | |
iter = 10_000_000 | |
Benchmark.bmbm do |x| | |
x.report('case: ') { iter.times { find_by_case(names.sample) } } | |
x.report('hash: ') { iter.times { find_by_hash(names.sample) } } | |
x.report('array: ') { iter.times { find_by_array(names.sample) } } | |
x.report('const get: ') { iter.times { find_by_const_get(names.sample) } } | |
x.report('constantize: ') { iter.times { names.sample.constantize } } | |
end | |
=begin | |
Rehearsal ------------------------------------------------- | |
case: 1.770000 0.000000 1.770000 ( 1.768994) | |
hash: 2.010000 0.000000 2.010000 ( 2.015642) | |
array: 1.840000 0.000000 1.840000 ( 1.842172) | |
const get: 2.830000 0.000000 2.830000 ( 2.832216) | |
constantize: 9.210000 0.010000 9.220000 ( 9.226218) | |
--------------------------------------- total: 17.670000sec | |
user system total real | |
case: 1.820000 0.000000 1.820000 ( 1.836090) | |
hash: 2.060000 0.000000 2.060000 ( 2.063271) | |
array: 1.820000 0.000000 1.820000 ( 1.824192) | |
const get: 2.810000 0.000000 2.810000 ( 2.802683) | |
constantize: 9.120000 0.010000 9.130000 ( 9.144598) | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment