reactiverse / es4x

🚀 fast JavaScript 4 Eclipse Vert.x
https://reactiverse.io/es4x/
Apache License 2.0
884 stars 75 forks source link

how to response a json object the right way #364

Closed beautimode closed 4 years ago

beautimode commented 4 years ago

Should I use JSON.stringify or is there better way?

router.get('/').handler((ctx) => {
  ctx.response().end(
    JSON.stringify({
      hello: 'world'
    })
  )
})

Using JSON.stringify drops the performance about 40% compares to ctx.response().end("hello world")

It's really often for a server to respond json data, but I can't find any hands-on API for the job. Is there a better way to do that?

pmlopes commented 4 years ago

JSON encoding as a performance penalty that is visible across all frameworks, here's one independent example:

JSON: https://www.techempower.com/benchmarks/#section=data-r19&hw=ph&test=json&l=zik0sf-1r text: https://www.techempower.com/benchmarks/#section=data-r19&hw=ph&test=plaintext&l=zik0sf-1r

One way we could improve this could be by writing a custom encoder that encodes directly to a buffer to be send to the network layer. But this would mean we would require users to not use JSON.stringify({...}) but something else like JSON.bufferify({...}).

pmlopes commented 4 years ago

Currently JSON.stringify should handle both native and js types.