Skip to content

Instantly share code, notes, and snippets.

@martinemde
Last active March 7, 2016 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save martinemde/b5878885b7a8ac93f4cf to your computer and use it in GitHub Desktop.
Save martinemde/b5878885b7a8ac93f4cf to your computer and use it in GitHub Desktop.
Compare s.hex.chr vs [s.hex].pack('C') vs [s.hex].pack(C)
require 'benchmark/ips'
require 'securerandom'
Benchmark.ips do |x|
C = 'C'.freeze
DATA = (1..1_000_000).map { SecureRandom.hex(1) }
x.report("hex.chr") do |times|
i = 0
while i < times
DATA[i%1_000_000].hex.chr
i += 1
end
end
x.report("array pack C") do |times|
i = 0
while i < times
[DATA[i%1_000_000].hex].pack(C)
i += 1
end
end
x.report("array pack 'C'") do |times|
i = 0
while i < times
[DATA[i%1_000_000].hex].pack('C')
i += 1
end
end
# Compare the iterations per second of the various reports!
x.compare!
end
Warming up --------------------------------------
hex.chr 112.897k i/100ms
array pack C 79.043k i/100ms
array pack 'C' 76.455k i/100ms
Calculating -------------------------------------
hex.chr 5.030M (±10.8%) i/s - 24.837M
array pack C 1.794M (±10.3%) i/s - 8.932M
array pack 'C' 1.535M (± 9.1%) i/s - 7.646M
Comparison:
hex.chr: 5030277.2 i/s
array pack C: 1793749.5 i/s - 2.80x slower
array pack 'C': 1535189.2 i/s - 3.28x slower
@martinemde
Copy link
Author

This has tested that no string of hex chars can raise with hex.chr. Only if you have more than 2 characters does it raise

SecureRandom.hex(1) generates like so;

100.times.map { SecureRandom.hex(1) }.join(" ")
=> "17 43 86 5c f4 8c a2 9d 9d c5 81 3a 2f a0 06 43 8e 0d aa d3 c6 cc 01 7b 07 ae 04 9d 5a 2d e4 2d 6f 3d 49 43 cf 0c 62 b5 8d eb c9 c8 a5 66 42 eb b2 44 ea 78 bd b4 ed 6f de 5a 08 52 18 fb eb e5 0e b6 e0 50 e4 a1 f0 ed a6 32 52 d8 06 55 64 a7 2d 64 e1 e5 2d 4f a7 38 0b e2 21 30 fc 68 98 7c c6 15 10 2f"

@bf4
Copy link

bf4 commented Mar 7, 2016

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment