Skip to content

Commit 5f45d63

Browse files
committed
constantize vs comparison
1 parent e8ac915 commit 5f45d63

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,30 @@ Comparison:
133133
module_eval with string: 1129.7 i/s - 1.19x slower
134134
```
135135

136+
##### `String#constantize` vs a comparison for inflection
137+
138+
ActiveSupport's [String#constantize](https://doc.bccnsoft.com/docs/rails-guides-4.2.1-en/active_support_core_extensions.html#constantize) "resolves the constant reference expression in its receiver".
139+
140+
[Read the rationale here](asdf)
141+
142+
```
143+
ruby 2.7.3p183 (2021-04-05 revision 6847ee089d) [x86_64-darwin20]
144+
145+
Calculating -------------------------------------
146+
using a Hash 8.641M (± 1.9%) i/s - 43.818M in 5.073094s
147+
using a case statement
148+
8.314M (± 3.1%) i/s - 41.587M in 5.007488s
149+
using an if statement
150+
8.295M (± 3.3%) i/s - 41.524M in 5.012041s
151+
String#constantize 2.365M (± 3.7%) i/s - 11.884M in 5.032603s
152+
153+
Comparison:
154+
using a Hash: 8640697.2 i/s
155+
using a case statement: 8313545.9 i/s - same-ish: difference falls within error
156+
using an if statement: 8295324.8 i/s - same-ish: difference falls within error
157+
String#constantize: 2365366.0 i/s - 3.65x (± 0.00) slower
158+
```
159+
136160
##### `raise` vs `E2MM#Raise` for raising (and defining) exeptions [code](code/general/raise-vs-e2mmap.rb)
137161

138162
Ruby's [Exception2MessageMapper module](http://ruby-doc.org/stdlib-2.2.0/libdoc/e2mmap/rdoc/index.html) allows one to define and raise exceptions with predefined messages.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
require "active_support/core_ext/string/inflections.rb"
2+
require "benchmark/ips"
3+
4+
class Foo; end
5+
6+
def fast3(s, h)
7+
klass = h[s]
8+
nil
9+
end
10+
11+
def fast2(s)
12+
klass = case s
13+
when "Foo"
14+
Foo
15+
end
16+
nil
17+
end
18+
19+
def fast(s)
20+
klass = Foo if s == "Foo"
21+
nil
22+
end
23+
24+
def slow(s)
25+
klass = s.constantize
26+
nil
27+
end
28+
29+
Benchmark.ips do |x|
30+
h = { "Foo" => Foo }
31+
32+
x.report("using a Hash") { fast3("Foo", h) }
33+
x.report("using a case statement") { fast2("Foo") }
34+
x.report("using an if statement") { fast("Foo") }
35+
x.report("String#constantize") { slow("Foo") }
36+
x.compare!
37+
end

0 commit comments

Comments
 (0)