fastruby / fast-ruby

:dash: Writing Fast Ruby :heart_eyes: -- Collect Common Ruby idioms.
https://github.com/fastruby/fast-ruby
5.67k stars 376 forks source link

inspect vs to_json for simple arrays #99

Closed iggant closed 8 years ago

iggant commented 8 years ago

If in array contain just strings can I use inspect instead of to_json

require 'benchmark/ips'

Benchmark.ips do |x|
x.report("inspect") do 
dd=['2', 4, 8, 4.8, 'yuunnnd', 89, 'rrrrrr', 'fsdfsdafasdfasdfasdfas']
dd.inspect
end
x.report('to_json') do
dd=['2', 4, 8, 4.8, 'yuunnnd', 89, 'rrrrrr', 'fsdfsdafasdfasdfasdfas']
dd.to_json
end
x.compare!
end
Warming up --------------------------------------
             inspect    13.918k i/100ms
             to_json     3.447k i/100ms
Calculating -------------------------------------
             inspect    201.462k (±14.1%) i/s -    988.178k
             to_json     39.050k (± 8.7%) i/s -    196.479k

Comparison:
             inspect:   201462.2 i/s
             to_json:    39049.5 i/s - 5.16x slower

=> #<Benchmark::IPS::Report:0x007fc689d1fe28 @entries=[#<Benchmark::IPS::Report::Entry:0x007fc6917d93a8 @label="inspect", @microseconds=5001375.913619995, @iterations=988178, @ips=201462.15039984178, @ips_sd=28314, @measurement_cycle=13918, @show_total_time=false>, #<Benchmark::IPS::Report::Entry:0x007fc693974558 @label="to_json", @microseconds=5068800.210952759, @iterations=196479, @ips=39049.53170380274, @ips_sd=3409, @measurement_cycle=3447, @show_total_time=false>], @data=nil>

Can I? Using inspect looks like unnatural but very fast, can some one explain about cons.

nateberkopec commented 8 years ago

If you can be absolutely sure the array contains only strings, numbers and booleans, I guess it would work. More of an app-specific hack though, I don't think it's appropriate for this repository.

ixti commented 8 years ago

As @nateberkopec said, it's app-specific. In some cases it might be OK, in most - just not. This is definitely out of scope of this repo. If you need faster JSON serializer, you can use oj:

require "benchmark/ips"
require "oj"

PAYLOAD = ['2', 4, 8, 4.8, 'yuunnnd', 89, 'rrrrrr', 'fsdfsdafasdfasdfasdfas']

Benchmark.ips do |x|
  x.report("inspect") { PAYLOAD.inspect }
  x.report("oj.dump") { Oj.dump PAYLOAD }

  x.compare!
end

the above will produce:

Calculating -------------------------------------
             inspect    19.877k i/100ms
             oj.dump    48.248k i/100ms
-------------------------------------------------
             inspect    267.444k (± 3.2%) i/s -      1.352M
             oj.dump    804.960k (± 6.1%) i/s -      4.005M

Comparison:
             oj.dump:   804959.9 i/s
             inspect:   267443.6 i/s - 3.01x slower

Also, there are in fact a lot more factors which can affect speed of to_json.