Skip to content

Commit

Permalink
Add String#start_with? vs String#[].==
Browse files Browse the repository at this point in the history
Closes #112
  • Loading branch information
jonathanhefner authored and JuanitoFatas committed Jun 15, 2016
1 parent cec53a2 commit f56798b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ Enumerable#sort_by (Symbol#to_proc): 25916.1 i/s
Of note, `to_proc` for 1.8.7 is considerable slower than the block format

```
$ ruby -v code/enumerable/inject-sum-vs-block.rb
$ ruby -v code/enumerable/inject-sum-vs-block.rb
ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin14]
Warming up --------------------------------------
inject symbol 1.893k i/100ms
Expand Down Expand Up @@ -884,6 +884,25 @@ Comparison:
String#=~: 891124.1 i/s - 3.30x slower
```

##### `String#start_with?` vs `String#[].==` [code](code/string/start_with-vs-substring-==.rb)

```
$ ruby -v code/string/end-string-checking-match-vs-end_with.rb
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]
Calculating -------------------------------------
String#start_with? 2.047M (± 4.5%) i/s - 10.242M in 5.015146s
String#[0, n] == 711.802k (± 7.3%) i/s - 3.551M in 5.019543s
String#[RANGE] == 651.751k (± 6.2%) i/s - 3.296M in 5.078772s
String#[0...n] == 427.207k (± 5.7%) i/s - 2.136M in 5.019245s
Comparison:
String#start_with?: 2046618.9 i/s
String#[0, n] ==: 711802.3 i/s - 2.88x slower
String#[RANGE] ==: 651751.2 i/s - 3.14x slower
String#[0...n] ==: 427206.8 i/s - 4.79x slower
```

##### `Regexp#===` vs `String#match` vs `String#=~` [code ](code/string/===-vs-=~-vs-match.rb)

> :warning: <br>
Expand Down
33 changes: 33 additions & 0 deletions code/string/start_with-vs-substring-==.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
require "benchmark/ips"

PREFIX = "_"
STRINGS = (0..9).map{|n| "#{PREFIX if n.odd?}#{n}" }

START_WITH = STRINGS.each_index.map do |i|
"STRINGS[#{i}].start_with?(PREFIX)"
end.join(";")

EQL_USING_LENGTH = STRINGS.each_index.map do |i|
# use `eql?` instead of `==` to prevent warnings
"STRINGS[#{i}][0, PREFIX.length].eql?(PREFIX)"
end.join(";")

RANGE = 0...PREFIX.length

EQL_USING_RANGE_PREALLOC = STRINGS.each_index.map do |i|
# use `eql?` instead of `==` to prevent warnings
"STRINGS[#{i}][RANGE].eql?(PREFIX)"
end.join(";")

EQL_USING_RANGE = STRINGS.each_index.map do |i|
# use `eql?` instead of `==` to prevent warnings
"STRINGS[#{i}][0...PREFIX.length].eql?(PREFIX)"
end.join(";")

Benchmark.ips do |x|
x.report("String#start_with?", START_WITH)
x.report("String#[0, n] ==", EQL_USING_LENGTH)
x.report("String#[RANGE] ==", EQL_USING_RANGE_PREALLOC)
x.report("String#[0...n] ==", EQL_USING_RANGE)
x.compare!
end

0 comments on commit f56798b

Please sign in to comment.