Created
August 6, 2013 20:36
-
-
Save caseyscarborough/6168366 to your computer and use it in GitHub Desktop.
Ruby snippet to test the fastest method of generating alphanumeric strings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
n = 10_000_000 | |
puts "\nGenerating random string of length #{n}:" | |
Benchmark.bm(9) do |x| | |
x.report('Method 1: ') do | |
range = [('a'..'z'),('A'..'Z'),('0'..'9')].map{ |i| i.to_a }.flatten | |
(0...n).map{ range[rand(range.length)] }.join | |
end | |
x.report('Method 2: ') do | |
range = [('a'..'z'),('A'..'Z'),('0'..'9')].map{ |i| i.to_a }.flatten | |
(0...n).map{ range.sample }.join | |
end | |
x.report('Method 3: ') do | |
range = [*'0'..'9',*'A'..'Z',*'a'..'z'] | |
Array.new(n){ range.sample }.join | |
end | |
x.report('Method 4: ') do | |
range = [*'0'..'9',*'A'..'Z',*'a'..'z'] | |
(0...n).map{ range.sample }.join | |
end | |
x.report('Method 5: ') do | |
range = ((48..57).to_a+(65..90).to_a+(97..122).to_a).map{ |i| i.chr } | |
Array.new(n){ range.sample }.join | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment