Skip to content

Instantly share code, notes, and snippets.

@jmdeldin
Created September 8, 2012 04:10
Show Gist options
  • Save jmdeldin/3671729 to your computer and use it in GitHub Desktop.
Save jmdeldin/3671729 to your computer and use it in GitHub Desktop.
Split vs. count
require 'benchmark'
N = 10_000_000
S = 'string,' * N
Benchmark.bmbm do |x|
x.report('#count') do
(length = S.count(',')) && (length + 1).times{|i| "line #{i} of #{length}" }
end
x.report('#split') do
split_s = S.split(',')
len = split_s.length
split_s.each_with_index{ |element, index| "line #{index} of #{len}"}
end
end
% ruby bench.rb
Rehearsal ------------------------------------------
#count 9.580000 0.000000 9.580000 ( 9.582891)
#split 13.090000 0.520000 13.610000 ( 13.614202)
-------------------------------- total: 23.190000sec
user system total real
#count 9.050000 0.260000 9.310000 ( 9.313300)
#split 11.690000 0.310000 12.000000 ( 11.999484)
@jmdeldin
Copy link
Author

jmdeldin commented Sep 8, 2012

With N = 100:

Rehearsal ------------------------------------------
#count   0.000000   0.000000   0.000000 (  0.000085)
#split   0.000000   0.000000   0.000000 (  0.000106)
--------------------------------- total: 0.000000sec

             user     system      total        real
#count   0.000000   0.000000   0.000000 (  0.000066)
#split   0.000000   0.000000   0.000000 (  0.000079)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment