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.
This commit is contained in:
Martin Hořeňovský
2026-07-23 19:10:14 +02:00
parent 46bdf1a04c
commit bb8873ccd7
+16 -3
View File
@@ -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<unsigned char>( '"' )] = true;
escape[static_cast<unsigned char>( '\\' )] = true;
escape[static_cast<unsigned char>( '\b' )] = true;
escape[static_cast<unsigned char>( '\f' )] = true;
escape[static_cast<unsigned char>( '\n' )] = true;
escape[static_cast<unsigned char>( '\r' )] = true;
escape[static_cast<unsigned char>( '\t' )] = true;
}
};
static constexpr EscapeLUT escapeLUT{};
static constexpr bool needsEscape( char c ) {
return escapeLUT.escape[static_cast<unsigned char>( c )];
}
static Catch::StringRef makeEscapeStringRef( char c ) {