Skip to content

Instantly share code, notes, and snippets.

@chuckremes
Created November 17, 2011 20:49
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 chuckremes/1374478 to your computer and use it in GitHub Desktop.
Save chuckremes/1374478 to your computer and use it in GitHub Desktop.
# Compare performance of pack/unpack versus JSON generate/parse
#
require 'rubygems'
require 'benchmark'
require 'json'
A = (0..1_000).to_a
org_array = []
json_array = []
packed_array = []
0.upto(100_000) do |i|
org_array << A
end
def pack_it(array)
array.pack('N*')
end
def unpack_it(string)
string.unpack('N*')
end
org_array.each { |array| json_array << JSON.fast_generate(array) }
org_array.each { |array| packed_array << pack_it(array) }
Benchmark.bmbm("JSON versus pack/unpack".size) do |x|
x.report("fast generate:") do
org_array.each { |array| JSON.fast_generate(array) }
end
x.report("pack:") do
org_array.each { |array| pack_it(array) }
end
x.report("parse:") do
json_array.each { |string| JSON.parse(string) }
end
x.report("unpack:") do
packed_array.each { |string| unpack_it(string) }
end
end
Chuck-Remess-Mac-Pro:pack_vs_json cremes$ ruby -v
jruby 1.6.3 (ruby-1.8.7-p330) (2011-07-07 965162f) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_26) [darwin-x86_64-java]
Chuck-Remess-Mac-Pro:pack_vs_json cremes$ ruby --server -J-Xmx3g bench.rb
Rehearsal ----------------------------------------------------------
fast generate: 27.855000 0.000000 27.855000 ( 27.855000)
pack: 3.114000 0.000000 3.114000 ( 3.114000)
parse: 62.146000 0.000000 62.146000 ( 62.147000)
unpack: 3.233000 0.000000 3.233000 ( 3.233000)
------------------------------------------------ total: 96.348000sec
user system total real
fast generate: 27.390000 0.000000 27.390000 ( 27.390000)
pack: 3.105000 0.000000 3.105000 ( 3.105000)
parse: 61.729000 0.000000 61.729000 ( 61.729000)
unpack: 3.337000 0.000000 3.337000 ( 3.336000)
Chuck-Remess-Mac-Pro:pack_vs_json cremes$ rvm default
Chuck-Remess-Mac-Pro:pack_vs_json cremes$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10.5.0]
Chuck-Remess-Mac-Pro:pack_vs_json cremes$ ruby bench.rb
Rehearsal ----------------------------------------------------------
fast generate: 12.740000 0.080000 12.820000 ( 12.819956)
pack: 5.870000 0.030000 5.900000 ( 5.893181)
parse: 24.960000 0.040000 25.000000 ( 25.026834)
unpack: 10.650000 0.010000 10.660000 ( 10.653586)
------------------------------------------------ total: 54.380000sec
user system total real
fast generate: 13.130000 0.050000 13.180000 ( 13.190665)
pack: 6.120000 0.010000 6.130000 ( 6.138026)
parse: 24.910000 0.050000 24.960000 ( 25.111740)
unpack: 10.840000 0.030000 10.870000 ( 10.913505)
Chuck-Remess-Mac-Pro:pack_vs_json cremes$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment