Make the index text of items() on arrays lazy

basic_json_view::items() on an array formatted every element's index with
std::to_string when the item was made, whether or not the loop asks for the
key. The item now keeps the position and makes the text on the first key()
call. Objects are not affected.

Iterating over the items of an array of 3000 numbers and reading only the values:
  Apple M1: 25.5 us -> 4.6 us (0.45 M -> ~0 net instructions)
  Linux x86-64 Ir (whole run), GCC 13 / Clang 18: 14.9 M -> 4.1 M / 15.3 M -> 4.6 M
Reading key() costs what it did (24.5 us).

Belongs to the PR "json_view: read-side speedups".

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
Niels Lohmann committed 2026-10-22 09:30:17 +02:00
1 parent 059de71cfd
commit c09fa3047d
3 files changed
+42 -16

No files matched your search

+10 -8
View File
@@ -5646,20 +5646,21 @@ class view_item
view_item(const iterator& it, std::size_t index)
: m_it(it)
{
if (!it.is_object_iterator())
{
m_index = std::to_string(index);
}
}
, m_position(index)
{}
/// the member key, or the element index for arrays
/// the member key, or the element index for arrays (as text made on the
/// first call, so that iterating over the values pays nothing for it)
string_view_t key() const
{
if (m_it.is_object_iterator())
{
return m_it.key();
}
if (m_index.empty())
{
m_index = std::to_string(m_position);
}
return string_view_t(m_index.data(), m_index.size());
}
@@ -5682,7 +5683,8 @@ class view_item
private:
iterator m_it;
std::string m_index{}; // NOLINT(readability-redundant-member-init)
std::size_t m_position; ///< the index of an array element
mutable std::string m_index{}; ///< the text of m_position, once key() was called // NOLINT(readability-redundant-member-init)
};
/// the range returned by basic_json_view::items()