Skip to content

Instantly share code, notes, and snippets.

@seejohnrun
Created July 27, 2012 15:10
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 seejohnrun/3188573 to your computer and use it in GitHub Desktop.
Save seejohnrun/3188573 to your computer and use it in GitHub Desktop.
MessagePack & JSON
require 'yajl'
require 'rest-client'
require 'zlib'
require 'msgpack'
require 'benchmark'
require 'colorize'
def compressed(d)
output = StringIO.new
gz = Zlib::GzipWriter.new(output)
gz.write(d)
gz.close
output.string
end
def benchmark_on(struct)
puts "\n-- ENCODING ----".yellow
Benchmark.bm do |x|
x.report('json') do
100_000.times { Yajl::Encoder.encode(struct) }
end
x.report('msg') do
100_000.times { struct.to_msgpack }
end
end
puts "\n-- DECODING ----".yellow
json_raw = Yajl::Encoder.encode(struct)
msg_raw = struct.to_msgpack
Benchmark.bm do |x|
x.report('json') do
100_000.times { Yajl::Parser.parse(json_raw) }
end
x.report('msg') do
100_000.times { MessagePack.unpack(msg_raw) }
end
end
end
def compare_on(struct)
msg = struct.to_msgpack
length = msg.length
clength = compressed(msg).length
factor = clength / length.to_f
puts "msg length: #{length} (#{clength} compressed - #{factor})"
msg = Yajl::Encoder.encode(struct)
length = msg.length
clength = compressed(msg).length
factor = clength / length.to_f
puts "json length: #{length} (#{clength} compressed - #{factor})"
end
access_token = 'your access token here'
puts '== Full facebook profile ===='.green
raw_data = RestClient.get "https://graph.facebook.com/me?access_token=#{access_token}"
struct = Yajl::Parser.parse(raw_data)
compare_on struct
benchmark_on struct
puts "\n== Facebook friends list ====".green
raw_data = RestClient.get "https://graph.facebook.com/me/friends?access_token=#{access_token}"
struct = Yajl::Parser.parse(raw_data)
compare_on struct
puts "\n== 100 groups of 100 7-letter words ====".green
alphabet = 'abcdefghijklmnopqrstuvwxyz'
struct = 100.times.map do
100.times.map do
7.times.map { alphabet[rand(alphabet.length)] }.join('')
end
end
compare_on struct
puts "\n== 100 groups of 100 7-digit numbers ====".green
alphabet = '123456789'
struct = 100.times.map do
100.times.map do
7.times.map { alphabet[rand(alphabet.length)] }.join('').to_i
end
end
compare_on struct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment