Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@casperisfine
Created March 8, 2023 12:45
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 casperisfine/5b75ba5d1e5154d785da4efdcc0527a4 to your computer and use it in GitHub Desktop.
Save casperisfine/5b75ba5d1e5154d785da4efdcc0527a4 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
CONSTS = {}
module Mod
1000.times do |i|
CONSTS["CONST_#{i}"] = i
const_set("CONST_#{i}", i)
end
end
require 'benchmark/ips'
module Inflector
class << self
def constantize(camel_cased_word)
Object.const_get(camel_cased_word)
end
def safe_constantize(camel_cased_word)
constantize(camel_cased_word)
rescue NameError => e
raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) ||
e.name.to_s == camel_cased_word.to_s)
rescue LoadError => e
message = e.respond_to?(:original_message) ? e.original_message : e.message
raise unless /Unable to autoload constant #{const_regexp(camel_cased_word)}/.match?(message)
end
end
end
class String
def safe_constantize
Inflector.safe_constantize(self)
end
end
Benchmark.ips do |x|
x.report("Hash#[]") { CONSTS["CONST_999"] }
x.report("const_get 1 sym") { Mod.const_get(:CONST_999) }
x.report("const_get 1 str") { Mod.const_get("CONST_999") }
x.report("const_get 2 str") { Object.const_get("Mod::CONST_999") }
x.report("safe_constantize") { "Mod::CONST_999".safe_constantize }
x.compare!(order: :baseline)
end
Warming up --------------------------------------
Hash#[] 1.479M i/100ms
const_get 1 sym 1.503M i/100ms
const_get 1 str 920.881k i/100ms
const_get 2 str 647.367k i/100ms
safe_constantize 485.857k i/100ms
Calculating -------------------------------------
Hash#[] 14.834M (± 2.5%) i/s - 75.417M in 5.087217s
const_get 1 sym 15.016M (± 4.8%) i/s - 76.653M in 5.119995s
const_get 1 str 9.126M (± 2.7%) i/s - 46.044M in 5.049378s
const_get 2 str 6.389M (± 7.1%) i/s - 31.721M in 5.002337s
safe_constantize 4.863M (± 1.1%) i/s - 24.779M in 5.095572s
Comparison:
Hash#[]: 14834315.0 i/s
const_get 1 sym: 15016010.6 i/s - same-ish: difference falls within error
const_get 1 str: 9126454.1 i/s - 1.63x slower
const_get 2 str: 6389107.4 i/s - 2.32x slower
safe_constantize: 4863389.2 i/s - 3.05x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment