From 46bdf1a04c92e7d34ee24f95d8d8a862498eede7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ho=C5=99e=C5=88ovsk=C3=BD?= Date: Thu, 23 Jul 2026 14:34:39 +0200 Subject: [PATCH] Optimize writing of non-string values to JSON In practice, the majority of values the JSON writer handles are strings, but this makes the code more obvious and can still provide a small speed-up. --- src/catch2/internal/catch_jsonwriter.cpp | 33 +++++++++++++++--------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/src/catch2/internal/catch_jsonwriter.cpp b/src/catch2/internal/catch_jsonwriter.cpp index d5122dbc..a33590f0 100644 --- a/src/catch2/internal/catch_jsonwriter.cpp +++ b/src/catch2/internal/catch_jsonwriter.cpp @@ -172,21 +172,30 @@ namespace Catch { } void JsonValueWriter::writeImpl( Catch::StringRef value, bool quote ) { - if ( quote ) { m_os << '"'; } - size_t current_start = 0; - for ( size_t i = 0; i < value.size(); ++i ) { - if ( needsEscape( value[i] ) ) { - if ( current_start < i ) { - m_os << value.substr( current_start, i - current_start ); + // Escaping only makes sense for actual strings, which are passed + // with `quote == true`. Non-quoted values are things like bools + // and numbers, which cannot create inputs that need escaping. + if ( !quote ) { + m_os << value; + } else { + m_os << '"'; + size_t current_start = 0; + for ( size_t i = 0; i < value.size(); ++i ) { + if ( needsEscape( value[i] ) ) { + if ( current_start < i ) { + m_os + << value.substr( current_start, i - current_start ); + } + m_os << makeEscapeStringRef( value[i] ); + current_start = i + 1; } - m_os << makeEscapeStringRef( value[i] ); - current_start = i + 1; } + if ( current_start < value.size() ) { + m_os << value.substr( current_start, + value.size() - current_start ); + } + m_os << '"'; } - if ( current_start < value.size() ) { - m_os << value.substr( current_start, value.size() - current_start ); - } - if ( quote ) { m_os << '"'; } } } // namespace Catch