Compare commits

..
Author SHA1 Message Date
Niels Lohmann 027d730547 Reserve the result of dump() in big steps once the output is big
dump() appended to an empty string, which reallocates and copies the output
each time it doubles; with glibc every new big block is fresh memory that is
faulted in page by page. dump() now uses its own output adapter: the first
write of at least 512 characters reserves 1 MiB, and four times as much
whenever that is not enough, up to 64 MiB. Smaller outputs never reserve.
String types without reserve() keep appending.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-29 12:28:26 +01:00
11 changed files with 230 additions and 183 deletions

No files matched your search

+5
View File
@@ -64,6 +64,10 @@ so the result can be larger than the value by a factor of its nesting depth (see
## Notes
Once the output reaches 512 characters, the result reserves 1 MiB, and four times as much whenever that is not enough,
up to 64 MiB. This saves copies and page faults while the string grows, but the returned string can have a much larger
`capacity()` than `size()`. Call `shrink_to_fit()` on a result that is kept for long.
Floating-point numbers are written with the fewest digits that read back as the same value (for `#!cpp double`; see
[number handling](../../features/types/number_handling.md#number-serialization)).
@@ -106,3 +110,4 @@ Binary values are serialized as an object containing two keys:
- Error handler `keep` added in version 3.13.0.
- Doubles are written with the shortest digits (Żmij instead of Grisu2) since version 3.13.0; about 0.1% of doubles are
written differently, most of them with fewer digits.
- The result reserves capacity for outputs of 512 characters or more since version 3.13.0.
@@ -25,6 +25,7 @@
#endif // JSON_NO_IO
#include <nlohmann/detail/macro_scope.hpp>
#include <nlohmann/detail/meta/cpp_future.hpp>
NLOHMANN_JSON_NAMESPACE_BEGIN
namespace detail
@@ -400,6 +401,68 @@ class output_string_adapter : public output_adapter_protocol<CharType>
StringType& str;
};
/*!
@brief output adapter for the string that basic_json::dump() returns
A string that grows by appending reallocates and copies its contents each time
it doubles, and with glibc every new big block is fresh memory that faults in
page by page. Once a single write of at least 512 characters arrives (a full
flush of the serializer's buffer or a long string, so the output is at least
that big), this adapter reserves 1 MiB, and four times as much whenever that is
not enough, until 64 MiB; beyond that the string grows by itself. Smaller
outputs never reserve. The capacity is tracked here, as StringType::capacity()
is not required; a StringType without reserve() just appends.
*/
template<typename CharType, typename StringType>
class output_dump_string_adapter : public output_adapter_protocol<CharType>
{
public:
explicit output_dump_string_adapter(StringType& s) noexcept
: str(s)
{}
void write_character(CharType c) override
{
str.push_back(c);
}
void write_characters(const CharType* s, std::size_t length) override
{
if (JSON_HEDLEY_UNLIKELY(length >= 512))
{
grow(str.size() + length);
}
str.append(s, length);
}
private:
void grow(const std::size_t needed)
{
const std::size_t first_reserve = 1048576; // 1 MiB
const std::size_t last_reserve = 64 * first_reserve;
if (needed > reserved && reserved < last_reserve)
{
const std::size_t next = reserved == 0 ? first_reserve : reserved * 4;
reserved = (std::max)(needed, next);
reserve_string(str, reserved, priority_tag<1> {});
}
}
template<typename String>
static auto reserve_string(String& string, std::size_t n, priority_tag<1> /*unused*/)
-> decltype(string.reserve(n), void())
{
string.reserve(n);
}
template<typename String>
static void reserve_string(String& /*string*/, std::size_t /*n*/, priority_tag<0> /*unused*/) noexcept
{}
StringType& str;
std::size_t reserved = 0;
};
/// @brief output sink forwarding to a type-erased output adapter
///
/// Wraps the polymorphic output_adapter_t so the same binary_writer template can
+1 -16
View File
@@ -628,11 +628,7 @@ run_found:
// covers the escapes of a typical document without regrowing it
wanted = (std::max)(wanted, (std::min)((static_cast<std::size_t>(m_end - m_begin) / 4) + 16, std::size_t{4096}));
}
const std::size_t size = (std::max)(m_doc.arena.size() * 2, wanted);
// (reserved before the resize writes it, so that a large arena gets huge pages)
m_doc.arena.reserve(size);
document_data::advise_huge(m_doc.arena.data(), m_doc.arena.capacity());
m_doc.arena.resize(size);
m_doc.arena.resize((std::max)(m_doc.arena.size() * 2, wanted));
m_arena_write = m_doc.arena.data() + used;
m_arena_end = m_doc.arena.data() + m_doc.arena.size();
}
@@ -1327,17 +1323,6 @@ template<typename FloatType, bool NulIsEnd>
inline bool build(document_data& d, const char* src, std::size_t size, bool comments, bool trailing_commas, bool sentinel, bool validate_only,
parse_failure& failure)
{
#if defined(__linux__) && defined(MADV_HUGEPAGE)
if (!(validate_only && !comments && !trailing_commas))
{
// a large index is reserved here, with huge pages (see document_data::reserve_huge())
const std::size_t n = estimate_nodes(src, size);
if (NLOHMANN_VIEW_UNLIKELY(n >= document_data::huge_min_bytes() / sizeof(node)))
{
d.reserve_huge(n);
}
}
#endif
if (validate_only && !comments && !trailing_commas)
{
// accept() of plain JSON: nothing is stored. The other option sets
@@ -8,9 +8,6 @@
#pragma once
#if defined(__linux__)
#include <sys/mman.h>
#endif
#include <array> // array
#include <cstddef> // size_t
#include <cstdint> // uint8_t, uint32_t
@@ -182,52 +179,6 @@ struct document_data
NLOHMANN_VIEW_THROW(std::bad_alloc());
}
/// a large block: transparent huge pages for its 2 MiB-aligned interior, so that writing it takes one page
/// fault per 2 MiB instead of one per 4 KiB (Linux with THP in "madvise" mode, the default of many
/// distributions; a no-op otherwise)
static NLOHMANN_VIEW_NOINLINE void advise_huge_now(const void* p, std::size_t size) noexcept
{
#if defined(__linux__) && defined(MADV_HUGEPAGE)
const std::uintptr_t huge = std::uintptr_t {2} << 20u;
const auto first = (reinterpret_cast<std::uintptr_t>(p) + huge - 1) & ~(huge - 1); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
const auto last = (reinterpret_cast<std::uintptr_t>(p) + size) & ~(huge - 1); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
if (last > first)
{
static_cast<void>(::madvise(reinterpret_cast<void*>(first), last - first, MADV_HUGEPAGE)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast,performance-no-int-to-ptr)
}
#else
static_cast<void>(p);
static_cast<void>(size);
#endif
}
/// the size from which advise_huge() asks for huge pages
static constexpr std::size_t huge_min_bytes() noexcept
{
return std::size_t{4} << 20u;
}
static NLOHMANN_VIEW_ALWAYS_INLINE void advise_huge(const void* p, std::size_t size) noexcept
{
if (NLOHMANN_VIEW_UNLIKELY(size >= huge_min_bytes()))
{
advise_huge_now(p, size);
}
}
/// reserve() for a large index, before the parse loop starts (which then finds the room it asks for): with
/// huge pages where advise_huge() gets them. Out of line and outside the parse loop, so that the loop's code
/// stays as it is.
NLOHMANN_VIEW_NOINLINE void reserve_huge(std::size_t n)
{
const node* const before = nodes;
reserve(n);
if (nodes != before)
{
advise_huge_now(nodes, node_capacity * sizeof(node));
}
}
/// make room for n nodes; keeps the first node_count nodes (throws
/// std::bad_alloc for a count that does not fit the address space,
/// instead of wrapping around in n * sizeof(node))
+1 -1
View File
@@ -2766,7 +2766,7 @@ public:
const error_handler_t error_handler = error_handler_t::strict) const
{
string_t result;
detail::output_string_adapter<char, string_t> string_adapter(result);
detail::output_dump_string_adapter<char, string_t> string_adapter(result);
if (indent >= 0)
{
+65 -1
View File
@@ -29739,6 +29739,8 @@ NLOHMANN_JSON_NAMESPACE_END
// #include <nlohmann/detail/macro_scope.hpp>
// #include <nlohmann/detail/meta/cpp_future.hpp>
NLOHMANN_JSON_NAMESPACE_BEGIN
namespace detail
@@ -30114,6 +30116,68 @@ class output_string_adapter : public output_adapter_protocol<CharType>
StringType& str;
};
/*!
@brief output adapter for the string that basic_json::dump() returns
A string that grows by appending reallocates and copies its contents each time
it doubles, and with glibc every new big block is fresh memory that faults in
page by page. Once a single write of at least 512 characters arrives (a full
flush of the serializer's buffer or a long string, so the output is at least
that big), this adapter reserves 1 MiB, and four times as much whenever that is
not enough, until 64 MiB; beyond that the string grows by itself. Smaller
outputs never reserve. The capacity is tracked here, as StringType::capacity()
is not required; a StringType without reserve() just appends.
*/
template<typename CharType, typename StringType>
class output_dump_string_adapter : public output_adapter_protocol<CharType>
{
public:
explicit output_dump_string_adapter(StringType& s) noexcept
: str(s)
{}
void write_character(CharType c) override
{
str.push_back(c);
}
void write_characters(const CharType* s, std::size_t length) override
{
if (JSON_HEDLEY_UNLIKELY(length >= 512))
{
grow(str.size() + length);
}
str.append(s, length);
}
private:
void grow(const std::size_t needed)
{
const std::size_t first_reserve = 1048576; // 1 MiB
const std::size_t last_reserve = 64 * first_reserve;
if (needed > reserved && reserved < last_reserve)
{
const std::size_t next = reserved == 0 ? first_reserve : reserved * 4;
reserved = (std::max)(needed, next);
reserve_string(str, reserved, priority_tag<1> {});
}
}
template<typename String>
static auto reserve_string(String& string, std::size_t n, priority_tag<1> /*unused*/)
-> decltype(string.reserve(n), void())
{
string.reserve(n);
}
template<typename String>
static void reserve_string(String& /*string*/, std::size_t /*n*/, priority_tag<0> /*unused*/) noexcept
{}
StringType& str;
std::size_t reserved = 0;
};
/// @brief output sink forwarding to a type-erased output adapter
///
/// Wraps the polymorphic output_adapter_t so the same binary_writer template can
@@ -42972,7 +43036,7 @@ public:
const error_handler_t error_handler = error_handler_t::strict) const
{
string_t result;
detail::output_string_adapter<char, string_t> string_adapter(result);
detail::output_dump_string_adapter<char, string_t> string_adapter(result);
if (indent >= 0)
{
+1 -65
View File
@@ -102,9 +102,6 @@
#if defined(__linux__)
#include <sys/mman.h>
#endif
#include <array> // array
#include <cstddef> // size_t
#include <cstdint> // uint8_t, uint32_t
@@ -526,52 +523,6 @@ struct document_data
NLOHMANN_VIEW_THROW(std::bad_alloc());
}
/// a large block: transparent huge pages for its 2 MiB-aligned interior, so that writing it takes one page
/// fault per 2 MiB instead of one per 4 KiB (Linux with THP in "madvise" mode, the default of many
/// distributions; a no-op otherwise)
static NLOHMANN_VIEW_NOINLINE void advise_huge_now(const void* p, std::size_t size) noexcept
{
#if defined(__linux__) && defined(MADV_HUGEPAGE)
const std::uintptr_t huge = std::uintptr_t {2} << 20u;
const auto first = (reinterpret_cast<std::uintptr_t>(p) + huge - 1) & ~(huge - 1); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
const auto last = (reinterpret_cast<std::uintptr_t>(p) + size) & ~(huge - 1); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
if (last > first)
{
static_cast<void>(::madvise(reinterpret_cast<void*>(first), last - first, MADV_HUGEPAGE)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast,performance-no-int-to-ptr)
}
#else
static_cast<void>(p);
static_cast<void>(size);
#endif
}
/// the size from which advise_huge() asks for huge pages
static constexpr std::size_t huge_min_bytes() noexcept
{
return std::size_t{4} << 20u;
}
static NLOHMANN_VIEW_ALWAYS_INLINE void advise_huge(const void* p, std::size_t size) noexcept
{
if (NLOHMANN_VIEW_UNLIKELY(size >= huge_min_bytes()))
{
advise_huge_now(p, size);
}
}
/// reserve() for a large index, before the parse loop starts (which then finds the room it asks for): with
/// huge pages where advise_huge() gets them. Out of line and outside the parse loop, so that the loop's code
/// stays as it is.
NLOHMANN_VIEW_NOINLINE void reserve_huge(std::size_t n)
{
const node* const before = nodes;
reserve(n);
if (nodes != before)
{
advise_huge_now(nodes, node_capacity * sizeof(node));
}
}
/// make room for n nodes; keeps the first node_count nodes (throws
/// std::bad_alloc for a count that does not fit the address space,
/// instead of wrapping around in n * sizeof(node))
@@ -2013,11 +1964,7 @@ run_found:
// covers the escapes of a typical document without regrowing it
wanted = (std::max)(wanted, (std::min)((static_cast<std::size_t>(m_end - m_begin) / 4) + 16, std::size_t{4096}));
}
const std::size_t size = (std::max)(m_doc.arena.size() * 2, wanted);
// (reserved before the resize writes it, so that a large arena gets huge pages)
m_doc.arena.reserve(size);
document_data::advise_huge(m_doc.arena.data(), m_doc.arena.capacity());
m_doc.arena.resize(size);
m_doc.arena.resize((std::max)(m_doc.arena.size() * 2, wanted));
m_arena_write = m_doc.arena.data() + used;
m_arena_end = m_doc.arena.data() + m_doc.arena.size();
}
@@ -2712,17 +2659,6 @@ template<typename FloatType, bool NulIsEnd>
inline bool build(document_data& d, const char* src, std::size_t size, bool comments, bool trailing_commas, bool sentinel, bool validate_only,
parse_failure& failure)
{
#if defined(__linux__) && defined(MADV_HUGEPAGE)
if (!(validate_only && !comments && !trailing_commas))
{
// a large index is reserved here, with huge pages (see document_data::reserve_huge())
const std::size_t n = estimate_nodes(src, size);
if (NLOHMANN_VIEW_UNLIKELY(n >= document_data::huge_min_bytes() / sizeof(node)))
{
d.reserve_huge(n);
}
}
#endif
if (validate_only && !comments && !trailing_commas)
{
// accept() of plain JSON: nothing is stored. The other option sets
+16
View File
@@ -484,6 +484,22 @@ TEST_CASE("alternative string type")
}
}
TEST_CASE("alternative string type with a big dump")
{
// dump() reserves capacity in the result once the output is big
alt_json j = alt_json::array();
nlohmann::json reference = nlohmann::json::array();
for (int i = 0; i < 300000; ++i)
{
j.push_back(i);
reference.push_back(i);
}
j.push_back(alt_string(600, 'x'));
reference.push_back(std::string(600, 'x'));
const std::string expected = reference.dump(2);
CHECK(j.dump(2) == expected);
}
TEST_CASE("alternative string type with json_view")
{
// regression test for #5994: basic_json_view::dump() called
+36
View File
@@ -800,6 +800,30 @@ class failing_adapter : public nlohmann::detail::output_adapter_protocol<char>
} // namespace
#endif
namespace
{
// a string type with only what the adapter of dump() needs, and no reserve()
struct appending_string
{
std::string str;
std::size_t size() const noexcept
{
return str.size();
}
void push_back(char c)
{
str.push_back(c);
}
void append(const char* s, std::size_t length)
{
str.append(s, length);
}
};
} // namespace
TEST_CASE("output adapters")
{
SECTION("writing a single character")
@@ -825,6 +849,18 @@ TEST_CASE("output adapters")
CHECK(as_string == "ef");
}
SECTION("the adapter of dump() with a string type without reserve()")
{
// dump() reserves capacity for big outputs only if the string type
// has reserve(); without it, the adapter just appends
appending_string as_string {std::string()};
nlohmann::detail::output_dump_string_adapter<char, appending_string> dump_adapter(as_string);
dump_adapter.write_character('g');
const std::string block(600, 'h');
dump_adapter.write_characters(block.data(), block.size());
CHECK(as_string.str == "g" + block);
}
#if !defined(JSON_NOEXCEPTION)
SECTION("a sink that is destroyed with characters left over")
{
-51
View File
@@ -598,54 +598,3 @@ TEST_CASE("json_view large objects")
CHECK(d.memory_usage() >= with_index / 2);
}
}
TEST_CASE("json_view large indexes and arenas")
{
// inputs whose index (and decoded strings) take several MiB: on Linux, these blocks are reserved before the
// parse loop and get transparent huge pages (document_data::reserve_huge(), advise_huge())
SECTION("an index of more than 4 MiB")
{
std::string text = "[";
for (int i = 0; i < 400000; ++i)
{
text += (i != 0 ? "," : "") + std::to_string(i);
}
text += ']';
json_document d = json_document::parse(text);
CHECK(d.node_count() == 400001);
CHECK(d.root().size() == 400000);
CHECK(d.root()[0].get<int>() == 0);
CHECK(d.root()[399999].get<int>() == 399999);
CHECK(json_document::accept(text));
// a reused document: a small input, then the large one again
d.read(std::string("[1,2]"));
CHECK(d.root().size() == 2);
d.read(text);
CHECK(d.root()[123456].get<int>() == 123456);
CHECK(d.root() == json::parse(text));
}
SECTION("decoded strings of more than 4 MiB")
{
// 2,000 strings of 3,000 bytes, each with escapes, so that every one is decoded into the arena
std::string s;
for (int i = 0; i < 1000; ++i)
{
s += "ab\\n";
}
std::string text = "[";
for (int i = 0; i < 2000; ++i)
{
text += (i != 0 ? ",\"" : "\"") + std::to_string(i) + s + "\"";
}
text += ']';
const json_document d = json_document::parse(text);
REQUIRE(d.root().size() == 2000);
const json expected = json::parse(text);
CHECK(d.root()[0].get<std::string>() == expected[0].get<std::string>());
CHECK(d.root()[1999].get<std::string>() == expected[1999].get<std::string>());
CHECK(d.root()[1999].get<std::string>().size() == 4 + 3000);
CHECK(d.root() == expected);
}
}
+42
View File
@@ -1717,3 +1717,45 @@ TEST_CASE("runs of multi-byte characters are escaped like the reference under en
}
}
}
TEST_CASE("dump() of outputs around the sizes where the result reserves capacity")
{
// the result reserves 1 MiB from the first write of at least 512
// characters, and four times as much whenever that is not enough; the
// output must not depend on it
const std::size_t mib = 1048576;
for (const std::size_t length :
{
std::size_t{0}, std::size_t{1}, std::size_t{509}, std::size_t{510}, std::size_t{511}, std::size_t{512},
std::size_t{513}, std::size_t{1023}, std::size_t{1024}, mib - 3, mib - 2, mib - 1, mib, mib + 1,
(4 * mib) - 2, (4 * mib) + 1
})
{
CAPTURE(length)
const std::string s(length, 'x');
const json j = s;
CHECK(j.dump() == "\"" + s + "\"");
}
// many writes of the serializer's buffer, compact and indented
for (const std::size_t count :
{
std::size_t{0}, std::size_t{1}, std::size_t{100}, std::size_t{200000}
})
{
CAPTURE(count)
json j = json::array();
std::string compact = "[";
std::string indented = "[";
for (std::size_t i = 0; i < count; ++i)
{
j.push_back(i);
compact += (i == 0 ? "" : ",") + std::to_string(i);
indented += (i == 0 ? "\n " : ",\n ") + std::to_string(i);
}
compact += "]";
indented += count == 0 ? "]" : "\n]";
CHECK(j.dump() == compact);
CHECK(j.dump(1) == indented);
}
}