Performance wise, which is better: .get with a block or without a block when parsing JSON?
#169
Answered
by
ioquatix
postmodern
asked this question in
Q&A
|
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|
...
endvs. client.get('/endpoint') do |response|
json = JSON.parse(response.read)
json.each do |value|
...
end
end |
Answered by
ioquatix
Jul 27, 2024
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. |
2 replies
Answer selected by
postmodern
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.