From 57890c381c09779d960a5242819acb32fdf2d53d Mon Sep 17 00:00:00 2001 From: Jonathan Hefner Date: Tue, 24 May 2016 18:43:37 -0500 Subject: [PATCH] Add String#start_with? vs String#[].== --- README.md | 18 ++++++++++++ code/string/start_with-vs-substring-==.rb | 34 +++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100755 code/string/start_with-vs-substring-==.rb diff --git a/README.md b/README.md index ae7c86a..b63533a 100644 --- a/README.md +++ b/README.md @@ -884,6 +884,24 @@ Comparison: String#=~: 891124.1 i/s - 3.30x slower ``` +##### `String#start_with?` vs `String#[].==` [code](code/string/start_with-vs-substring-==.rb) + +``` +ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-cygwin] + +Calculating ------------------------------------- + String#start_with? 739.364k (± 0.5%) i/s - 3.720M in 5.031116s + String#[0, n] == 346.112k (± 0.2%) i/s - 1.753M in 5.063586s + String#[RANGE] == 318.284k (± 0.2%) i/s - 1.612M in 5.066202s + String#[0...n] == 220.535k (± 0.1%) i/s - 1.110M in 5.033769s + +Comparison: + String#start_with?: 739364.0 i/s + String#[0, n] ==: 346112.1 i/s - 2.14x slower + String#[RANGE] ==: 318283.6 i/s - 2.32x slower + String#[0...n] ==: 220534.9 i/s - 3.35x slower +``` + ##### `Regexp#===` vs `String#match` vs `String#=~` [code ](code/string/===-vs-=~-vs-match.rb) > :warning:
diff --git a/code/string/start_with-vs-substring-==.rb b/code/string/start_with-vs-substring-==.rb new file mode 100755 index 0000000..7008d42 --- /dev/null +++ b/code/string/start_with-vs-substring-==.rb @@ -0,0 +1,34 @@ +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