Skip to content
This repository was archived by the owner on Mar 24, 2026. It is now read-only.

[Crystal] Optimize JSON responses - #6584

Merged
NateBrady23 merged 1 commit into
TechEmpower:masterfrom
matthewmcgarvey:fix-crystal-json
May 20, 2021
Merged

NateBrady23 merged 1 commit into
TechEmpower:masterfrom
matthewmcgarvey:fix-crystal-json

Conversation

@matthewmcgarvey

Copy link
Copy Markdown
Contributor

response.print(...) is WAY faster than .to_json(response) for some reason. Local test on /json went from 80k per second to 220k per second.

@vlazar

vlazar commented May 16, 2021

Copy link
Copy Markdown
Contributor

@matthewmcgarvey Would it actually make sense to wait till crystal-lang/crystal#10716 gets merged in? I hope it would make into Crystal 1.1.0, which shouldn't be too far ahead.

I believe using .to_json(response) is a current recommended way for performant code I nCrystal and maybe it's better to keep benchmark code as it is and just update to Crystal version where this is fixed once it's released?

@matthewmcgarvey

matthewmcgarvey commented May 16, 2021 •

Copy link
Copy Markdown
Contributor Author

@vlazar if the difference in performance really is due to the multiple calling of flush, then this change will still be faster since calling io.print(...) does not flush the io.

I've looked into most of the major frameworks and they all do it this way as well.

Mainly, this has made me wonder why HTTP::Server::Response is an IO at all.

@vlazar

vlazar commented May 16, 2021

Copy link
Copy Markdown
Contributor

OTOH .to_json creates new objects while .to_json(response) does not? I guess the performance impact could be different depending on the size of the serialized object.

@matthewmcgarvey

Copy link
Copy Markdown
Contributor Author

@nbrady-techempower This is ready to go 👍

@NateBrady23
NateBrady23 merged commit 6769bf6 into TechEmpower:master May 20, 2021
@matthewmcgarvey
matthewmcgarvey deleted the fix-crystal-json branch May 20, 2021 15:35
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants