fix: track the JSON length instead of recounting it

Every append found the end of the buffer with strlen(), up to four
times per append and four appends per field, so building a response
cost the square of its size. /discovery fills a 4 KB buffer and spent
about 195 ms of its ~210 ms there (shades 126 ms, groups 69 ms), all on
the async_tcp task that serves every socket and web request.

Keep the length in the formatter and write every append at the end
through one helper. The web response and socket event subclasses and
ControllerChunker use the tracked length too. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
cjkas 2026-10-12 16:04:13 +02:00
parent 55b1db4508
commit a8bb377957
5 changed files with 86 additions and 33 deletions

View file

@ -8,6 +8,8 @@ class JsonFormatter {
protected:
char *buff;
size_t buffSize;
// What is in buff, kept so appending never has to strlen() the buffer.
size_t _len = 0;
bool _headersSent = false;
uint8_t _objects = 0;
uint8_t _arrays = 0;
@ -16,6 +18,9 @@ class JsonFormatter {
bool _overflow = false;
char _numbuff[25] = {0};
virtual void _safecat(const char *val, bool escape = false);
// Appends val at buff + _len. vlen is what it takes, including the quotes
// when escaped; the caller has made sure it fits.
void _appendAt(const char *val, bool escape, size_t vlen);
void _appendNumber(const char *name);
public:
bool overflowed() const { return _overflow; }