Skip to content

Instantly share code, notes, and snippets.

@fallwith
Created November 3, 2022 20:51
Show Gist options
  • Save fallwith/e284fabc845cbf288039b3248f6cbd6c to your computer and use it in GitHub Desktop.
Save fallwith/e284fabc845cbf288039b3248f6cbd6c to your computer and use it in GitHub Desktop.
Ruby gzip compression testing of text
require 'zlib'
CHARACTERS = ['a'..'z', 'A'..'Z', 0..9].map(&:to_a).flatten.freeze
TRIES = 10_000
BYTE_RANGE = 50..1000
savings = TRIES.times.each_with_object([]) do |_, arr|
string = (0...rand(BYTE_RANGE)).map { CHARACTERS[rand(CHARACTERS.size)] }.join
gzipped = Zlib.gzip(string)
arr << (1 - gzipped.size.to_f / string.size) * 100
end
puts "Average savings for #{TRIES} tries with strings ranging from " \
"#{BYTE_RANGE.first} to #{BYTE_RANGE.last} bytes in length:" \
"\n\n#{savings.sum / savings.size}%"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment