gvariant: Avoid malloc/free in valid_format_string()

Any extremely common use-case of valid_format_string() is validation
when using GVariantBuilder. The optimal-case there is that there is
no programming error and thus the fast path should match.

This creates a fast path for that case without substantial change to the
GVariant type-checking case by checking for a non-NULL GVariant. It then
proceeds to hoist the actual scan directly without type allocation.

Locally this single change reduces wallclock time in a single-threaded
benchmark using GVariantBuilder by 17%.
This commit is contained in:
Christian Hergert 2024-09-20 13:05:46 -07:00
parent 84b6f747cb
commit 7e362048a3

View File

@ -4652,6 +4652,15 @@ valid_format_string (const gchar *format_string,
const gchar *endptr;
GVariantType *type;
/* An extremely common use-case is checking the format string without
* caring about the value specifically. Provide a fast-path for this to
* avoid the malloc/free overhead.
*/
if G_LIKELY (value == NULL &&
g_variant_format_string_scan (format_string, NULL, &endptr) &&
(single || *endptr == '\0'))
return TRUE;
type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))