简体   繁体   中英

Javascript performances for property access : undefined vs false

Working with collections, I'm wondering what is the best practice between: Not defining a property (when it is missing) or defining it as false.

Example:

First case:

[
{"age":42}, // first item
{} // second item, age is undefined
]

Second case:

[
{"age":42}, // first item
{"age":false} // second item, age is explicitly set to false
]

Then using this collection with MongoDB or within an AngularJS repeat or whatever, I might do the following:

if (item.age){ doSomething();}

Where both option are correct.

I would personally say the first case is interesting because if we do not have an information we do not specify it but is there a cost, flaw or risk for finding a missing property ?

...but is there a cost, flaw or risk for finding a missing property ?

Nothing of any significance, no. Technically, when you look up a property that isn't on the object, the JavaScript engine has to then check the object's prototype (and its prototype, and so on), which in theory is a bit slower (theory and reality may be different), but the prototype chain would have to be deep , or you'd have to be doing this for hundreds of thousands of objects in a tight time-sensitive loop, for it to matter — if then.

If it really bothers you to leave the property off, rather than false , you might consider undefined or null . They're also falsey, but (to my mind, anyway) they imply less. Note that JSON doesn't have undefined , though, if you're using JSON somewhere in your app.

Remember the axiom: "Don't optimize prematurely." This is particularly apt in the JavaScript world, because what makes something faster on one JavaScript engine can make it slower on another. And so the answer to just about any JavaScript performance question is: Test it and see.

Here's a test on objects that are directly derived from Object.prototype ; results on three major browsers:

在此输入图像描述

Here's another test , testing the very unrealistic case of a 20-deep prototype hierarchy:

在此输入图像描述

It consist from your performance needs. If you want to optimise data storage, you should decrease data size. If scripting time is more important the right way is setting false as default value. But second way can provide the errors, hidden from error logs. So you can have problems in debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM