Skip to content

Instantly share code, notes, and snippets.

@rafbm
Last active December 11, 2015 18:49
Show Gist options
  • Save rafbm/4644755 to your computer and use it in GitHub Desktop.
Save rafbm/4644755 to your computer and use it in GitHub Desktop.
Benchmarking the creation of an array of digits, lowercase and uppercase letters
require 'benchmark'
# Which is faster for creating an array of numbers, lowercase and uppercase letters?
Benchmark.benchmark Benchmark::CAPTION, 12 do |bm|
bm.report 'String#split' do
100_000.times { '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('') }
end
bm.report 'Range#to_a' do
100_000.times { ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a }
end
end
__END__
Results:
user system total real
String#split 3.740000 0.040000 3.780000 ( 3.784892)
Range#to_a 1.790000 0.010000 1.800000 ( 1.810478)
Range FTW!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment