Use JSON.generate() instead to improve performance#115
Merged
Conversation
It seems it is more efficient using JSON.generate() instead of the #to_json method. ### benchmark ```ruby require 'bundler/inline' gemfile do source 'https://rubygems.org' gem 'benchmark-ips' gem 'json' end json =<<~JSON { "method": "$/steep/typecheck/progress", "params": { "guid": "8d4c15ce-33ad-40d8-bef4-8713f29cab5b", "path": "/home/watson/prj/gruff/lib/gruff/store/basic_data.rb", "target": "lib", "diagnostics": [] }, "jsonrpc": "2.0" } JSON data = JSON.parse(json) puts "** JSON version #{JSON::VERSION} **" Benchmark.ips do |x| x.report('to_json') { data.to_json } x.report('JSON.generate') { JSON.generate(data) } x.compare! end ``` ### result ```sh $ ruby json.rb ** JSON version 2.11.3 ** ruby 3.4.3 (2025-04-14 revision d0b7e5b6a0) +PRISM [x86_64-linux] Warming up -------------------------------------- to_json 293.738k i/100ms JSON.generate 335.385k i/100ms Calculating ------------------------------------- to_json 2.887M (± 1.4%) i/s (346.41 ns/i) - 14.687M in 5.088761s JSON.generate 3.366M (± 1.0%) i/s (297.10 ns/i) - 17.105M in 5.082281s Comparison: JSON.generate: 3365882.0 i/s to_json: 2886757.9 i/s - 1.17x slower ``` ### environmet - OS: Manjaro Linux x86_64 - Kernel: 6.14.4-1-MANJARO - Compiler: gcc 14.2.1 20250207 - Ruby: ruby 3.4.3
Owner
|
I confirmed it's 1.25x faster on my end, thanks! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
It seems it is more efficient using JSON.generate() instead of the #to_json method.
benchmark
result
environmet