Skip to content

Instantly share code, notes, and snippets.

@therealadam therealadam/maps.rb
Created Mar 25, 2016

Embed
What would you like to do?
Can you chain maps and eat cake too?
Allocations -------------------------------------
null 0/0 alloc/ret 0/0 strings/ret
mega no work 1/0 alloc/ret 0/0 strings/ret
mega w/ locals 1446/114 alloc/ret 50/50 strings/ret
chained 1334/0 alloc/ret 50/0 strings/ret
lazy chained 2102/0 alloc/ret 50/0 strings/ret
Warming up --------------------------------------
null 151.895k i/100ms
mega no work 6.384k i/100ms
mega w/ locals 135.000 i/100ms
chained 133.000 i/100ms
lazy chained 105.000 i/100ms
Calculating -------------------------------------
null 10.550M (± 6.3%) i/s - 52.556M
mega no work 67.528k (± 5.1%) i/s - 338.352k
mega w/ locals 1.403k (± 3.4%) i/s - 7.020k
chained 1.362k (± 2.8%) i/s - 6.916k
lazy chained 1.040k (± 5.0%) i/s - 5.250k
require "benchmark/ipsa"
require "digest/md5"
text = File.read("/etc/passwd")
lines = text.split
# sillysum obfuscates a file by:
#
# - rot13'ing each line
# - upcasing each line
# - calculating the MD5 of each rot13'd line
# - concatenating all the MD5s
#
# It is really silly.
ROT13_INPUT = 'A-Za-z'
ROT13_OUTPUT = 'N-ZA-Mn-za-m'
Benchmark.ipsa do |x|
x.report("null") do
end
x.report("mega no work") do
lines.map {}
end
x.report("mega w/ locals") do
lines.map { |l|
rot13 = l.tr(ROT13_INPUT, ROT13_OUTPUT)
upcase = rot13.upcase
Digest::MD5.hexdigest(upcase)
}.join("")
end
x.report("chained") do
lines.
map { |line| line.tr(ROT13_INPUT, ROT13_OUTPUT) }.
map { |line| line.upcase }.
map { |line| Digest::MD5.hexdigest(line) }.
join("")
end
x.report("lazy chained") do
lines.lazy.
map { |line| line.tr(ROT13_INPUT, ROT13_OUTPUT) }.
map { |line| line.upcase }.
map { |line| Digest::MD5.hexdigest(line) }.
to_a.
join("")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.