From bb8873ccd710d55a4fa7cc02d710fdb4da69cfb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ho=C5=99e=C5=88ovsk=C3=BD?= Date: Thu, 23 Jul 2026 19:01:53 +0200 Subject: [PATCH] JSONWriter uses LUT for faster checking if a char needs escaping This provides nice speedup when writing strings that don't need escaping, at about 6% in Debug build and ~40% in Release build. If the strings do need escaping the speedup is much smaller, at ~1% in Debug and ~6% in Release build, as the cost of actually escaping the strings dwarves the cost of checking. --- src/catch2/internal/catch_jsonwriter.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/catch2/internal/catch_jsonwriter.cpp b/src/catch2/internal/catch_jsonwriter.cpp index a33590f0..190a978c 100644 --- a/src/catch2/internal/catch_jsonwriter.cpp +++ b/src/catch2/internal/catch_jsonwriter.cpp @@ -16,9 +16,22 @@ namespace Catch { namespace { - static bool needsEscape( char c ) { - return c == '"' || c == '\\' || c == '\b' || c == '\f' || - c == '\n' || c == '\r' || c == '\t'; + struct EscapeLUT { + bool escape[256] = {}; + constexpr EscapeLUT() { + escape[static_cast( '"' )] = true; + escape[static_cast( '\\' )] = true; + escape[static_cast( '\b' )] = true; + escape[static_cast( '\f' )] = true; + escape[static_cast( '\n' )] = true; + escape[static_cast( '\r' )] = true; + escape[static_cast( '\t' )] = true; + } + }; + static constexpr EscapeLUT escapeLUT{}; + + static constexpr bool needsEscape( char c ) { + return escapeLUT.escape[static_cast( c )]; } static Catch::StringRef makeEscapeStringRef( char c ) {