This repository was archived by the owner on Mar 24, 2026. It is now read-only.
[ruby/json] Use JSON.generate instead of Object#to_json#10782
Merged
Conversation
JSON.generate is faster than calling Object#to_json.
```ruby
require 'benchmark/ips'
require 'json'
Benchmark.ips do |x|
x.config(warmup: 2, time: 5)
x.report("to_json symbol") do
{ message: 'Hello, World!' }.to_json
end
x.report("to_json string") do
{ 'message' => 'Hello, World!' }.to_json
end
x.report("JSON.generate symbol") do
JSON.generate({ message: 'Hello, World!' })
end
x.report("JSON.generate string") do
JSON.generate({ 'message' => 'Hello, World!' })
end
x.compare!
end
```
```
ruby 3.4.8 (2025-12-17 revision 995b59f666) +PRISM [arm64-darwin24]
Warming up --------------------------------------
to_json symbol 330.723k i/100ms
to_json string 325.411k i/100ms
JSON.generate symbol 490.246k i/100ms
JSON.generate string 495.752k i/100ms
Calculating -------------------------------------
to_json symbol 3.219M (± 8.2%) i/s (310.65 ns/i) - 16.205M in 5.097780s
to_json string 3.250M (± 3.5%) i/s (307.67 ns/i) - 16.271M in 5.012989s
JSON.generate symbol 4.966M (± 1.5%) i/s (201.35 ns/i) - 25.003M in 5.035419s
JSON.generate string 4.973M (± 2.1%) i/s (201.10 ns/i) - 25.283M in 5.086778s
Comparison:
JSON.generate string: 4972636.6 i/s
JSON.generate symbol: 4966478.7 i/s - same-ish: difference falls within error
to_json string: 3250251.2 i/s - 1.53x slower
to_json symbol: 3219106.9 i/s - 1.54x slower
```
msmith-techempower
approved these changes
Feb 18, 2026
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 subscribe to this conversation on GitHub.
Already have an account?
Sign in.
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.
JSON.generate is faster than calling Object#to_json.