-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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