Skip to content

Instantly share code, notes, and snippets.

@kbrock
Created May 30, 2018 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbrock/8fe4f7ba12ff99fd871c16623a0ab96a to your computer and use it in GitHub Desktop.
Save kbrock/8fe4f7ba12ff99fd871c16623a0ab96a to your computer and use it in GitHub Desktop.
Compare string to array
method nil speed str speed
?split:[] 9,761,148.9 i/s 2,869,972.9 i/s 3.40x
&.split||[] 9,271,343.0 i/s same 2,879,248.1 i/s 3.39x
&&split||[] 9,096,687.7 i/s same 2,941,303.8 i/s 3.32x
to_s.split 4,288,858.0 i/s 2.28x 2,822,293.7 i/s 3.46x
ruby -v
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]
require 'benchmark/ips'
require 'active_support/all'
# | method | nil |speed | str | speed|
# |----------------|-----------------|------|-----------------|------|
# |`?split:[]` | 9,761,148.9 i/s | | 2,869,972.9 i/s | 3.40x|
# |`&.split\|\|[]` | 9,271,343.0 i/s | same | 2,879,248.1 i/s | 3.39x|
# |`&&split\|\|[]` | 9,096,687.7 i/s | same | 2,941,303.8 i/s | 3.32x|
# |`to_s.split` | 4,288,858.0 i/s | 2.28x| 2,822,293.7 i/s | 3.46x|
NSTRING = nil
DELIMITER='/'.freeze
STRING="ab/cd".freeze
Benchmark.ips do |x|
x.report(data: nil, method: "to_s.split") { NSTRING.to_s.split(DELIMITER) }
x.report(data: nil, method: "?split:[]") { NSTRING ? NSTRING.split(DELIMITER) : []}
x.report(data: nil, method: "&&split||[]") { NSTRING && NSTRING.split(DELIMITER) || []}
x.report(data: nil, method: "&.split||[]") { NSTRING&.split(DELIMITER) || []}
x.report(data: :str, method: "to_s.split") { STRING.to_s.split(DELIMITER) }
x.report(data: :str, method: "?split:[]") { STRING ? STRING.split(DELIMITER) : []}
x.report(data: :str, method: "&&split||[]") { STRING && STRING.split(DELIMITER) || []}
x.report(data: :str, method: "&.split||[]") { STRING&.split(DELIMITER) || []}
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment