Make the default of value() with a C string only if the member is missing

basic_json_view::value(key, "text") and value(pointer, "text") built a
std::string from the default first and passed it on, so a call allocated
for the default even when the member exists, and copied it again when it
does not. They now look the member up and make the result directly: from the
member if there is one, else from the C string. Behavior, including the
exceptions, is the same.

Two calls (member found, member missing) with a 40 character default, Apple M1:
  1.6 K -> 0.7 K instructions
  Linux x86-64 Ir (500 rounds), GCC 13 / Clang 18: 2.46 M -> 2.22 M / 2.40 M -> 2.15 M

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:19 +02:00
1 parent c09fa3047d
commit 69e3a7ef50
3 files changed
+36 -4

No files matched your search

+13 -2
View File
@@ -7731,7 +7731,13 @@ class basic_json_view
string_t value(string_view_t key, const char* default_value) const
{
return value(key, string_t(default_value));
if (NLOHMANN_VIEW_UNLIKELY(!is_object()))
{
detail::view::throw_type_error(306, "cannot use value() with ", type_name());
}
// (the default is made only if there is no such member)
const basic_json_view r = lookup(key);
return r.is_discarded() ? string_t(default_value) : r.template get<string_t>();
}
/// the value a JSON pointer refers to converted to T, or the default
@@ -7750,7 +7756,12 @@ class basic_json_view
string_t value(const json_pointer& ptr, const char* default_value) const
{
return value(ptr, string_t(default_value));
if (NLOHMANN_VIEW_UNLIKELY(!is_structured()))
{
detail::view::throw_type_error(306, "cannot use value() with ", type_name());
}
const basic_json_view r = detail::view::resolve_pointer(*this, detail::json_pointer_access::reference_tokens(ptr), detail::view::pointer_mode::value);
return r.is_discarded() ? string_t(default_value) : r.template get<string_t>();
}
/// the first element or member value; a primitive value itself. Throws