Skip to content

Instantly share code, notes, and snippets.

@JarLowrey
Created July 16, 2017 20:34
Show Gist options
  • Save JarLowrey/f77b651b90a00e9a202265e20f20c929 to your computer and use it in GitHub Desktop.
Save JarLowrey/f77b651b90a00e9a202265e20f20c929 to your computer and use it in GitHub Desktop.
Benchmark for Ruby String ID creation
require 'benchmark'
#RESULTS - 100k iterations
# user system total real
# 0.590000 0.000000 0.590000 ( 0.594802) <- create_id_num - int to radix
# 0.270000 0.000000 0.270000 ( 0.267420) <- create_id_str - choosing random characters
@radix = ('0'..'9').to_a + ('a'..'z').to_a + ['$','-','_','+','!','*','(',')',','] #URL safe, lowercase characters
def self.custom_radix_to_s val, digits
digits = digits.to_a unless digits.respond_to? :[]
radix = digits.length
raise ArgumentError, "radix must have at least two digits" if radix < 2
i = val.to_i
out = []
begin
rem = i % radix
i /= radix
out << digits[rem..rem]
end until i == 0
out.reverse.join
end
def self.create_id_num(max_len)
max = @radix.length**max_len #what is the highest value given a set number of characters? For base 10 and 3 characters, it's 10*10*10 = 10**3
id = rand(1..max) #choose random ID in allowed range
id = self.custom_radix_to_s(id, @radix) #convert base 10 ID to custom base
return id
end
def self.create_id_str(max_len)
id = ""
(1..max_len).each do |i|
id.concat(@radix.sample)
end
return id
end
iterations = 100000
max_len = 8
Benchmark.bm do |bm|
bm.report do
iterations.times do
create_id_num(max_len)
end
end
bm.report do
iterations.times do
create_id_str(max_len)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment