Skip to content

Instantly share code, notes, and snippets.

@kuldeepaggarwal
Created December 6, 2013 06:33
Show Gist options
  • Save kuldeepaggarwal/7819494 to your computer and use it in GitHub Desktop.
Save kuldeepaggarwal/7819494 to your computer and use it in GitHub Desktop.
Difference between ranges and array
require "benchmark"
char_collection = Hash.new (0)
TIMES = 10000
input_string = "123ABc ifuy fdtgbj\h vhkkkktvcv_*^%$# yku13234"
lowercase = ('a'..'z').to_a
uppercase = ('A'..'Z').to_a
digits = ('0'..'9').to_a
lcase = ('a'..'z')
ucase = ('A'..'Z')
dig = ('0'..'9')
Benchmark.bmbm do |test|
test.report ("array include") do
TIMES.times do |x|
input_string.each_char do |char|
case
when lowercase.include?(char)
char_collection['lowercase'] += 1
when uppercase.include?(char)
char_collection['uppercase'] += 1
when digits.include?(char)
char_collection['digits'] += 1
else
char_collection['special_characters'] += 1
end
end
char_collection
end
end
test.report ("array case") do
TIMES.times do |x|
input_string.each_char do |char|
case char
when lowercase
char_collection['lowercase'] += 1
when uppercase
char_collection['uppercase'] += 1
when digits
char_collection['digits'] += 1
else
char_collection['special_characters'] += 1
end
end
char_collection
end
end
test.report("inline ranges") do
TIMES.times do |x|
input_string.each_char do |char|
case char
when 'a'..'z'
char_collection['lowercase'] += 1
when 'A'..'Z'
char_collection['uppercase'] += 1
when '0'..'9'
char_collection['digit'] += 1
else
char_collection['special_characters'] += 1
end
end
char_collection
end
end
test.report ("preinitialized ranges") do
TIMES.times do |x|
input_string.each_char do |char|
case char
when lcase
char_collection['lowercase'] += 1
when ucase
char_collection['uppercase'] += 1
when dig
char_collection['digits'] += 1
else
char_collection['special_characters'] += 1
end
end
char_collection
end
end
end
Rehearsal ---------------------------------------------------------
array include 0.900000 0.000000 0.900000 ( 0.902879)
array case 0.390000 0.000000 0.390000 ( 0.383773)
inline ranges 0.660000 0.000000 0.660000 ( 0.665557)
preinitialized ranges 0.350000 0.000000 0.350000 ( 0.345596)
------------------------------------------------ total: 2.300000sec
user system total real
array include 0.910000 0.000000 0.910000 ( 0.917236)
array case 0.390000 0.010000 0.400000 ( 0.384864)
inline ranges 0.660000 0.000000 0.660000 ( 0.662120)
preinitialized ranges 0.340000 0.000000 0.340000 ( 0.342905)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment