Is it possible to skip hasOwnProperty () when first checking Object.prototype?

We have to use hasOwnProperty()

when iterating over the keys of an object, because it Object.prototype

can get dirty, which, through prototype inheritance, will also pollute the keys of all objects.

So, if I'm not polluting Object.prototype

, I have to skip hasOwnProperty()

that slows down the for-in loops.This will simplify the code too.

The idea, first check that Object.prototype

is not dirty, then do not use hasOwnProperty()

.

Checking that Object.prototype

it was not dirty is done with the following function. I will call this in a strategic place in my code that is sometimes executed during script execution (for example, before I am about to process a bunch of data). This feature is just a guard warning me if something bad has been done to Object.prototype

:

/* jshint -W089 */  // http://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement/
var checkObjectPrototypeNotAugmented = function() {
    /* jshint unused:false */   // Because key is considered unused
    // Check if there is any enumerable property on Object.prototype:
    for(var key in Object.prototype) {
        throw new Error("Object.prototype has been augmented with keys: " + Object.prototype.keys());
    }
};

      

Note. I am posting a comment /* jshint -W089 */

so jshint wont complains about the lackhasOwnProperty()

.

Question: Is this normal? Is there anything else I should be careful about? Or what can I improve?


Now, some guidelines:

Here are 3 jsPerf tests that show the profit for objects with different number of properties:

Note. The check Object.prototype

is performed every time the properties of the object are iterated over. In a real situation, the test only needs to be executed once: when the full page is loaded (and then from time to time to make sure no script has been accidentally changed Object.prototype

). Therefore, in real life you will get the performance of the "Reference" test. But this shows that even when the test runs, it stays faster.

Interesting results:

  • does not use hasOwnProperty()

    either gives the same speed or faster depending on the browser.
  • even with only 1 property access , checking Object.protoype

    before each "in-in" loop might be faster in any browser than hasOwnProperty()

    ! (But I don't recommend always checking Object.prototype

    like this)

Related: We can also see that usage Object.keys()

can be even faster in some browsers for large objects, but it can also be slower for small objects. But usage Object.keys()

forces you to either support browsers> = IE 9 or increase Object.prototype

with polyfill in IE <= 8. So for old browser compatibility you have to choose either Object.keys()

or checkObjectPrototypeNotAugmented()

.

+3


source to share





All Articles