Skip to content

Instantly share code, notes, and snippets.

@bf4
Forked from martinemde/bench.rb
Created March 7, 2016 16:34
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 bf4/bc34dc67b38696249fac to your computer and use it in GitHub Desktop.
Save bf4/bc34dc67b38696249fac 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment