Sometimes I need to generate random numbers in Sketchup, but the Rubocop Sketchup cops warn that this can cause terrible performance, particularly on Windows. So far it has seemed like it can be slow, but I haven’t actually profiled it.
Previously, ThomThom and others have warned about Sketchup freezing for multiple minutes if using OpenSSL based solutions.
So here are some alternatives to SecureRandom and OpenSSL random number generation:
require 'benchmark' require 'securerandom' require 'base64' iterations = 10_000 Benchmark.bmbm do |bm| bm.report('Securerandom') do iterations.times do SecureRandom.urlsafe_base64 end end bm.report('base64') do iterations.times do Base64.urlsafe_encode64(Random.new.bytes(16)) end end bm.report('fake random') do iterations.times do rand(0x1000000000000000000000000000000000000000).to_s(36) end end end
My results show that SecureRandom seems to be passably fast in Ruby2.2 enabled Sketchup versions on Windows, though I haven’t tested others. At this point I’m not sure the suggestion to avoid it is still valid on newer versions of Sketchup. An alternative, using
Random.new.bytes(16), however, performs much worse and should probably be added to recommendations to avoid.
Meanwhile, the real star is using the native
Kernel#rand with an enormous number and then converting it to a base36 string. I found this trick in the Rails core code.
Try it yourself and see.
Choices are to generate a safe, 128-bit GUID that would be suitable anywhere, (uses ASCII and urlsafe characters).