Skip to content

Instantly share code, notes, and snippets.

@nbibler
Created January 30, 2019 17:08
Show Gist options
  • Save nbibler/952bef5f859d73c1378f68f137de493f to your computer and use it in GitHub Desktop.
Save nbibler/952bef5f859d73c1378f68f137de493f to your computer and use it in GitHub Desktop.
Ruby Digest::MD5 update vs hexdigest comparison
#!/usr/bin/env ruby -w
# frozen_string_literal: true
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'benchmark-memory'
end
require 'benchmark'
require 'benchmark/memory'
require 'securerandom'
require 'digest/md5'
ITERATIONS = 1_000
STRING_COUNT = 10_000
STRING_PARTS = Array.new(STRING_COUNT).map { SecureRandom.alphanumeric(100) }
SINGLE_STRING = STRING_PARTS.join("\n")
Benchmark.bmbm do |b|
b.report('update') do
ITERATIONS.times do
digest = Digest::MD5.new
STRING_PARTS.each { |p| digest.update(p) }
digest.hexdigest
end
end
b.report('single large string') do
ITERATIONS.times do
Digest::MD5.hexdigest(SINGLE_STRING)
end
end
end
Benchmark.memory do |b|
b.report('update') do
ITERATIONS.times do
digest = Digest::MD5.new
STRING_PARTS.each { |p| digest.update(p) }
digest.hexdigest
end
end
b.report('single large string') do
ITERATIONS.times do
Digest::MD5.hexdigest(SINGLE_STRING)
end
end
b.compare!
end
Rehearsal -------------------------------------------------------
update 2.874825 0.001647 2.876472 ( 2.877840)
single large string 1.356260 0.000497 1.356757 ( 1.357062)
---------------------------------------------- total: 4.233229sec
user system total real
update 2.806647 0.001140 2.807787 ( 2.808370)
single large string 1.280238 0.000906 1.281144 ( 1.282102)
Calculating -------------------------------------
update 193.000k memsize ( 0.000 retained)
4.000k objects ( 0.000 retained)
2.000 strings ( 0.000 retained)
single large string 153.000k memsize ( 0.000 retained)
3.000k objects ( 0.000 retained)
2.000 strings ( 0.000 retained)
Comparison:
single large string: 153000 allocated
update: 193000 allocated - 1.26x more
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment