MatthewWid / better-sse

⬆ Dead simple, dependency-less, spec-compliant server-sent events implementation for Node, written in TypeScript.
MIT License
485 stars 14 forks source link

Update Session to buffer internal field writes until dispatch #35

Closed MatthewWid closed 2 years ago

MatthewWid commented 2 years ago

Update Session to, instead of invoking res.write on each method call, write the field value to an internal string (or byte) buffer and then only send that buffer over the socket once the dispatch method is called.

During benchmarking it has been observed that calling res.write has a significant impact on performance, and calling it on each method call is unnecessary. Therefore, dispatch should actually dispatch only when it is called, instead of just artificially dispatching over the wire by writing an additional newline character to the socket.

This is probably (?) a breaking change as data is being written over the wire differently and implementations of the event source API that are not exactly spec compliant may produce different behaviours than before.

Otherwise this change is more than worth it as it will improve speed, lower bandwidth usage (no excess TCP segments and ACKs sent) and be more intuitive as now dispatch will be the final say in whether data is actually dispatched or not, whereas before data was actually dispatched to the client but just not recognized until it was called.

MatthewWid commented 2 years ago

I am deciding to split the functionality of dispatch into two separate methods for the sake of simplicity of the API and clarity of aligning to the terminology used in the specification, as well as making the implementation of the new buffer feature easier.

dispatch will now only write a newline to the buffer, and the new flush method will actually flush the buffer data to the client, instead of both of those things happening in the one dispatch.