Performance wise, which is better: .get
with a block or without a block when parsing JSON?
#169
-
I'm curious which is better, in theory, performance wise for parsing JSON responses?
response = client.get('/endpoint')
json = JSON.parse(response.read)
response.close
json.each do |value|
...
end vs. client.get('/endpoint') do |response|
json = JSON.parse(response.read)
json.each do |value|
...
end
end |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
It's generally safer to use the block form if you can since the response will be closed correctly in (almost) every case (except fatal, unrecoverable errors). There should be no difference in performance. However, the code in the first example is unsafe, as you don't have an ensure block to close the connection. If the JSON fails to parse, you may leak the response which is bad. |
Beta Was this translation helpful? Give feedback.
It's generally safer to use the block form if you can since the response will be closed correctly in (almost) every case (except fatal, unrecoverable errors). There should be no difference in performance. However, the code in the first example is unsafe, as you don't have an ensure block to close the connection. If the JSON fails to parse, you may leak the response which is bad.