Skip to content

Commit e860f60

Browse files
authored
Merge pull request #200 from wasaylor/constantize-vs-comparison
String#constantize vs simple comparison
2 parents e8ac915 + c0ac0fe commit e860f60

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,25 @@ 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://guides.rubyonrails.org/active_support_core_extensions.html#constantize) "resolves the constant reference expression in its receiver".
139+
140+
[Read the rationale here](https://github.com/fastruby/fast-ruby/pull/200)
141+
142+
```
143+
ruby 2.7.3p183 (2021-04-05 revision 6847ee089d) [x86_64-darwin20]
144+
145+
Calculating -------------------------------------
146+
using an if statement
147+
8.124M (± 1.8%) i/s - 41.357M in 5.092437s
148+
String#constantize 2.462M (± 2.4%) i/s - 12.315M in 5.004089s
149+
150+
Comparison:
151+
using an if statement: 8123851.3 i/s
152+
String#constantize: 2462371.2 i/s - 3.30x (± 0.00) slower
153+
```
154+
136155
##### `raise` vs `E2MM#Raise` for raising (and defining) exeptions [code](code/general/raise-vs-e2mmap.rb)
137156

138157
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: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
require "active_support/core_ext/string/inflections.rb"
2+
require "benchmark/ips"
3+
4+
class Foo; end
5+
6+
def fast(s)
7+
klass = Foo if s == "Foo"
8+
nil
9+
end
10+
11+
def slow(s)
12+
klass = s.constantize
13+
nil
14+
end
15+
16+
Benchmark.ips do |x|
17+
x.report("using an if statement") { fast("Foo") }
18+
x.report("String#constantize") { slow("Foo") }
19+
x.compare!
20+
end

0 commit comments

Comments
 (0)