[njs] Slightly optimized njs_object_keys_array().

Valentin Bartenev vbart at nginx.com
Sat Dec 1 19:32:14 UTC 2018


details:   https://hg.nginx.org/njs/rev/4a543ed58c95
branches:  
changeset: 681:4a543ed58c95
user:      Valentin Bartenev <vbart at nginx.com>
date:      Sat Dec 01 22:32:33 2018 +0300
description:
Slightly optimized njs_object_keys_array().

There is no need to iterate over the object properties second time if after
the first attempt we know that it contains no enumerable properties.

Also removed surplus conditions.

diffstat:

 njs/njs_object.c |  19 ++++++++++---------
 1 files changed, 10 insertions(+), 9 deletions(-)

diffs (61 lines):

diff -r e713f648ef71 -r 4a543ed58c95 njs/njs_object.c
--- a/njs/njs_object.c	Fri Nov 30 17:52:02 2018 +0300
+++ b/njs/njs_object.c	Sat Dec 01 22:32:33 2018 +0300
@@ -888,7 +888,7 @@ njs_object_keys(njs_vm_t *vm, njs_value_
 njs_array_t *
 njs_object_keys_array(njs_vm_t *vm, const njs_value_t *value)
 {
-    uint32_t           i, n, length, keys_length;
+    uint32_t           i, n, length, keys_length, properties;
     njs_value_t        *string;
     njs_array_t        *keys, *array;
     nxt_lvlhsh_t       *hash;
@@ -930,15 +930,14 @@ njs_object_keys_array(njs_vm_t *vm, cons
         break;
     }
 
+    /* GCC 4 and Clang 3 complain about uninitialized hash. */
+    hash = NULL;
+    properties = 0;
+
     if (nxt_fast_path(njs_is_object(value))) {
         nxt_lvlhsh_each_init(&lhe, &njs_object_hash_proto);
         hash = &value->data.u.object->hash;
 
-    } else {
-        hash = NULL;
-    }
-
-    if (nxt_fast_path(hash != NULL)) {
         for ( ;; ) {
             prop = nxt_lvlhsh_each(hash, &lhe);
 
@@ -947,9 +946,11 @@ njs_object_keys_array(njs_vm_t *vm, cons
             }
 
             if (prop->type != NJS_WHITEOUT && prop->enumerable) {
-                keys_length++;
+                properties++;
             }
         }
+
+        keys_length += properties;
     }
 
     keys = njs_array_alloc(vm, keys_length, NJS_ARRAY_SPARE);
@@ -966,13 +967,13 @@ njs_object_keys_array(njs_vm_t *vm, cons
             }
         }
 
-    } else if (length != 0) {
+    } else {
         for (i = 0; i < length; i++) {
             njs_uint32_to_string(&keys->start[n++], i);
         }
     }
 
-    if (nxt_fast_path(hash != NULL)) {
+    if (nxt_fast_path(properties != 0)) {
         nxt_lvlhsh_each_init(&lhe, &njs_object_hash_proto);
 
         for ( ;; ) {


More information about the nginx-devel mailing list