From 56a50e147dabdb57459a19c6c00f194b2ac49d24 Mon Sep 17 00:00:00 2001 From: Vincent Bernat Date: Sat, 15 Feb 2014 17:44:02 +0100 Subject: [PATCH] Micro-optimization for JSON_STRICT when no optional key is used The previous commit introduced a loop on all input keys to check the strict mode. We can avoid this if we don't expect an optional key. In this case, we fallback to the previous method to compare the length of the set of expected keys and the length of the parsed keys. --- src/pack_unpack.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/pack_unpack.c b/src/pack_unpack.c index abed654..af381a5 100644 --- a/src/pack_unpack.c +++ b/src/pack_unpack.c @@ -350,6 +350,7 @@ static int unpack_object(scanner_t *s, json_t *root, va_list *ap) { int ret = -1; int strict = 0; + int gotopt = 0; /* Use a set (emulated by a hashtable) to check that all object keys are accessed. Checking that the correct number of keys @@ -406,7 +407,7 @@ static int unpack_object(scanner_t *s, json_t *root, va_list *ap) next_token(s); if(token(s) == '?') { - opt = 1; + opt = gotopt = 1; next_token(s); } @@ -437,10 +438,16 @@ static int unpack_object(scanner_t *s, json_t *root, va_list *ap) const char *key; json_t *value; long unpacked = 0; - json_object_foreach(root, key, value) { - if(!hashtable_get(&key_set, key)) { - unpacked++; + if (gotopt) { + /* We have optional keys, we need to iter on each key */ + json_object_foreach(root, key, value) { + if(!hashtable_get(&key_set, key)) { + unpacked++; + } } + } else { + /* No optional keys, we can just compare the number of items */ + unpacked = (long)json_object_size(root) - (long)key_set.size; } if (unpacked) { set_error(s, "", "%li object item(s) left unpacked", unpacked);