Skip to content

Commit 69a5185

Browse files
committed
Use JSON.generate() instead to improve performance
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
1 parent 529cbfc commit 69a5185

File tree

1 file changed

+2
-2
lines changed
  • lib/language_server/protocol/transport/io

1 file changed

+2
-2
lines changed

lib/language_server/protocol/transport/io/writer.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ def initialize(io)
1111
end
1212

1313
def write(response)
14-
response_str = response.merge(
14+
response_str = JSON.generate(response.merge(
1515
jsonrpc: "2.0"
16-
).to_json
16+
))
1717

1818
headers = {
1919
"Content-Length" => response_str.bytesize

0 commit comments

Comments
 (0)