Skip to content

Instantly share code, notes, and snippets.

@sdogruyol
Last active April 4, 2016 08:23
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 sdogruyol/1f29c779ac1b17b01a71b9cd310935f9 to your computer and use it in GitHub Desktop.
Save sdogruyol/1f29c779ac1b17b01a71b9cd310935f9 to your computer and use it in GitHub Desktop.
require "benchmark"
require "json"
class MenuItem
def self.all
h = {
"name": "Serdar",
"age": 27,
"email": "dogruyolserdar@gmail.com",
"skills": ["ruby", "rails", "crystal", "kemal"]
}
array = [] of (typeof(h))
1000.times { array << h }
array
end
end
Benchmark.ips do |x|
x.report "Mapping" do
MenuItem.all.map do |mi|
{
"name": mi["name"],
"age": mi["age"],
"email": mi["email"],
"skills": mi["skills"]
}
end.to_json
end
x.report "IO" do
String.build do |io|
MenuItem.all.each do |mi|
io.json_object do |object|
object.field "name", mi["name"]
object.field "age", mi["age"]
object.field "email", mi["email"]
object.field "skills" do
io.json_array do |array|
(mi["skills"] as Array).each { |item| array << item }
end
end
end
end
end
end
end
@sdogruyol
Copy link
Author

crystal build --release json_serialization_benchmark.cr -o benchmark
./benchmark

Results

Mapping 893.39  (± 3.71%)  2.05× slower
     IO   1.83k (± 2.43%)       fastest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment