Iteration through javascript HashTable without loss of optimization

According to section 5.2.1 of this article: Optimization Killers

Doing this disables optimization in V8:

function hashTableIteration() {
    var hashTable = {"-": 3};
    for(var key in hashTable);
}

and the author says:

An object goes into hash table mode, for example, when you add too many properties dynamically (external constructor), delete properties, use properties that cannot be valid identifiers, etc. In other words, when you use an object as if it were a table hash, it will be turned into a hash table. Passing such an object to input-in is not. You can determine if an object is in hash table mode by invoking console.log(%HasFastProperties(obj))when the -allow-natives-syntax flag is enabled in Node.JS.

My question is, what is the correct way to iterate using the keys of a hash table object in javascript, so that the optimization doesn't turn off?

+4
source share
2 answers

It seems that the answer lies at the bottom of the same article.

Workaround: Always use Object.keys and iterate over the array using for loop. If you really need all the properties of the entire prototype circuit, make an isolated helper function:

function inheritedKeys(obj) {
  var ret = [];
  for(var key in obj) {
    ret.push(key);
  }
  return ret; 
}

If you pass an object to in-in mode, this is not just an enumerated value that will punish the entire containing function.

From what I understood, an isolated function would help optimize the rest of the process. Only the function inheritedkeyswill not be optimized in the example below.

function someFunction(someObj) {
    var keys = inheritedKeys(someObj),
        i = 0,
        len = keys.length;

    for (; i < len; i++) {
        //some computation
    }

}
+3

, Object.keys . , -, .

: , .

var keys = Object.keys(myObj);

for (var i = 0; i < keys.length; i++) {
    var value = myObj[keys[i]];
}
+3

Source: https://habr.com/ru/post/1546025/


All Articles