Project

General

Profile

Actions

Bug #12373

closed

Optimize CSV#shift

Added by ksss (Yuki Kurihara) about 6 years ago. Updated about 5 years ago.

Status:
Closed
Priority:
Normal
Target version:
ruby -v:
ruby 2.4.0dev (2016-05-11 trunk 54976) [x86_64-darwin15]
[ruby-core:75462]

Description

I think that str1.start_with?(str2) is faster than str1[0] == str2.
Because str1.start_with?(str2) just call String#start_with?, But str1[0] == str2 call String#[], make new String object and call String#==.

(The patch is csv-shift.patch)

Benchmark results.

csv-benchmark.rb make temp CSV file and call CSV#each method(inner call CSV#shift)

$ ruby csv-benchmark.rb
Warming up --------------------------------------
       old_csv_shift     1.000  i/100ms
       new_csv_shift     1.000  i/100ms
Calculating -------------------------------------
       old_csv_shift      0.444  (± 0.0%) i/s -      3.000  in   6.759200s
       new_csv_shift      0.479  (± 0.0%) i/s -      3.000  in   6.264069s

Comparison:
       new_csv_shift:        0.5 i/s
       old_csv_shift:        0.4 i/s - 1.08x slower

string-start_with.rb is a micro benchmark for str1[0] == str2 and str1.start_with?(str2)

$ ruby string-start_with.rb
Warming up --------------------------------------
           a[0] == b    90.881k i/100ms
    a.start_with?(b)   115.557k i/100ms
Calculating -------------------------------------
           a[0] == b      1.836M (± 3.8%) i/s -      9.179M in   5.006568s
    a.start_with?(b)      3.183M (± 4.2%) i/s -     15.947M in   5.018654s

Comparison:
    a.start_with?(b):  3183386.0 i/s
           a[0] == b:  1836263.5 i/s - 1.73x slower

Of course $ make test-all TESTS="test/csv/*" passed


Files

csv-benchmark.rb (561 Bytes) csv-benchmark.rb ksss (Yuki Kurihara), 05/12/2016 12:39 AM
old_csv_shift.rb (5.1 KB) old_csv_shift.rb ksss (Yuki Kurihara), 05/12/2016 12:39 AM
new_csv_shift.rb (5.11 KB) new_csv_shift.rb ksss (Yuki Kurihara), 05/12/2016 12:39 AM
string-start_with.rb (215 Bytes) string-start_with.rb ksss (Yuki Kurihara), 05/12/2016 12:39 AM
csv-shift.patch (434 Bytes) csv-shift.patch ksss (Yuki Kurihara), 05/12/2016 12:41 AM
csv-shift-1.patch (1.15 KB) csv-shift-1.patch ksss (Yuki Kurihara), 05/12/2016 02:11 PM
csv-shift-2.patch (1.2 KB) csv-shift-2.patch ksss (Yuki Kurihara), 05/12/2016 02:11 PM
csv-shift-3.patch (2.13 KB) csv-shift-3.patch ksss (Yuki Kurihara), 05/12/2016 02:12 PM
csv-shift-hsbt.path (2.05 KB) csv-shift-hsbt.path hsbt (Hiroshi SHIBATA), 05/16/2017 08:22 AM
Actions

Also available in: Atom PDF