Skip to content

Instantly share code, notes, and snippets.

@eagleas
Created June 6, 2011 11:25
Show Gist options
  • Save eagleas/1010092 to your computer and use it in GitHub Desktop.
Save eagleas/1010092 to your computer and use it in GitHub Desktop.
Quick test
$: << File.expand_path("../../lib", __FILE__)
require 'database_cleaner'
require 'mongoid'
require 'mongoid-rspec'
require 'mongoid_token'
require 'benchmark'
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("mongoid_token_benchmark")
end
DatabaseCleaner.strategy = :truncation
# start benchmarks
@token_length = 32
@times = 10000
class Link
include Mongoid::Document
include Mongoid::Token
token :length => @token_length, :contains => :alphanumeric
end
Link.destroy_all
puts "-- Alphanumeric token of length #{@token_length} (#{62**@token_length} possible tokens)"
Benchmark.bm do |b|
b.report("#{@times} records old "){ @times.times{ Link.new.send(:generate_token, @token_length, :alphanumeric) } }
def Link.generate_token(size, characters)
(1..size).collect { (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }.join
end
b.report("#{@times} records kernel"){ @times.times{ Link.new.send(:generate_token, @token_length, :alphanumeric) } }
def Link.generate_token(size, characters)
chars = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).map(&:to_s)
(0...size).collect { chars[Kernel.rand(chars.length)] }.join
end
b.report("#{@times} records chars "){ @times.times{ Link.new.send(:generate_token, @token_length, :alphanumeric) } }
def Link.generate_token(size, characters)
ActiveSupport::SecureRandom.base64(size*2).gsub(/(\/|\+|\-)/, '')[0..size-1]
end
b.report("#{@times} records base64"){ @times.times{ Link.new.send(:generate_token, @token_length, :alphanumeric) } }
end
$ ruby spec/benchmark_methods.rb
-- Alphanumeric token of length 32 (2272657884496751345355241563627544170162852933518655225856 possible tokens)
user system total real
10000 records old 1.520000 0.010000 1.530000 ( 1.544356)
10000 records kernel 1.510000 0.010000 1.520000 ( 1.517105)
10000 records chars 1.550000 0.000000 1.550000 ( 1.552146)
10000 records base64 1.550000 0.000000 1.550000 ( 1.549400)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment