Skip to content

Instantly share code, notes, and snippets.

@drbrain
Forked from phlipper/base62_benchmark.rb
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drbrain/9191efa47ecc6b5d51f1 to your computer and use it in GitHub Desktop.
Save drbrain/9191efa47ecc6b5d51f1 to your computer and use it in GitHub Desktop.
require "all_your_base"
require "benchmark/ips"
require "minitest/autorun"
require "securerandom"
BASE62_CHARS = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D",
"E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z"
]
def old_impl
o = [('0'..'9'), ('a'..'z'), ('A'..'Z')].map { |i| i.to_a }.flatten
(0...22).map { o[SecureRandom.random_number(o.length)] }.join
end
def new_impl
bytes = SecureRandom.random_bytes(22)
"".tap do |str|
bytes.each_byte.each { |b| str << BASE62_CHARS[b.to_i % 62] }
end
end
def all_your_base
uuid = SecureRandom.uuid.gsub(/\-/, '').to_i(16)
AllYourBase::Are.convert_from_base_10(uuid, radix: 62)
end
# benchmarks
Benchmark.ips do |x|
x.report("old impl") do
old_impl
end
x.report("all your base") do
all_your_base
end
x.report("new impl") do
new_impl
end
x.compare!
end
# tests
class TestBase62 < MiniTest::Unit::TestCase
def test_the_new_impl_uuid_size_is_always_22
100_000.times do
uuid = new_impl
assert_equal 22, uuid.size
end
end
def test_the_new_impl_uuid_size_is_unique
uuids = 100_000.times.map { new_impl }
assert_equal 100_000, uuids.size
assert_equal 100_000, uuids.uniq.size
end
def test_the_old_impl_uuid_size_is_always_22
100_000.times do
uuid = old_impl
assert_equal 22, uuid.size
end
end
def test_the_all_your_base_uuid_size_is_always_22
100_000.times do
uuid = all_your_base
assert_equal 22, uuid.size
end
end
end
% ruby base62_benchmark.rb
Calculating -------------------------------------
old impl 1.012k i/100ms
all your base 3.280k i/100ms
new impl 13.918k i/100ms
-------------------------------------------------
old impl 10.192k (± 6.0%) i/s - 51.612k
all your base 33.896k (± 4.8%) i/s - 170.560k
new impl 167.665k (± 4.8%) i/s - 848.998k
Comparison:
new impl: 167665.2 i/s
all your base: 33895.9 i/s - 4.95x slower
old impl: 10191.9 i/s - 16.45x slower
Run options: --seed 19017
# Running tests:
...F
Finished tests in 11.605460s, 0.3447 tests/s, 17233.6125 assertions/s.
1) Failure:
test_the_all_your_base_uuid_size_is_always_22(TestBase62) [foo.rb:77]:
Expected: 22
Actual: 21
4 tests, 200004 assertions, 1 failures, 0 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment