From 95424664ab33b8d0c71102f12f4b710a65aa9a87 Mon Sep 17 00:00:00 2001 From: Niels Lohmann Date: Wed, 11 Nov 2026 18:25:19 +0100 Subject: [PATCH] Fill the std::u8string with resize and indexing instead of push_back The push_back loop is not vectorized: reading a 1 kB string took about 2.2 us against 0.39 us with resize and direct element access (clang -O2). Signed-off-by: Niels Lohmann --- include/nlohmann/detail/conversions/from_json.hpp | 4 ++-- single_include/nlohmann/json.hpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/nlohmann/detail/conversions/from_json.hpp b/include/nlohmann/detail/conversions/from_json.hpp index eb1f3d189..951f1a287 100644 --- a/include/nlohmann/detail/conversions/from_json.hpp +++ b/include/nlohmann/detail/conversions/from_json.hpp @@ -798,10 +798,10 @@ inline void from_json(const BasicJsonType& j, std::basic_string ret(s.get_allocator()); - ret.reserve(size); + ret.resize(size); for (std::size_t i = 0; i < size; ++i) { - ret.push_back(static_cast(static_cast(data[i]))); + ret[i] = static_cast(static_cast(data[i])); } s = std::move(ret); } diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 45c9b92a6..3a887e376 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -6941,10 +6941,10 @@ inline void from_json(const BasicJsonType& j, std::basic_string ret(s.get_allocator()); - ret.reserve(size); + ret.resize(size); for (std::size_t i = 0; i < size; ++i) { - ret.push_back(static_cast(static_cast(data[i]))); + ret[i] = static_cast(static_cast(data[i])); } s = std::move(ret); }