Nur Rony
Nur Rony

Reputation: 8083

Accessing properties by variable assignment or calling function?

I was reading accessing object properties as variable section from Airbnb's style guide which says it is good accessing properties like below

var luke = {
  jedi: true,
  age: 28
};

function getProp(prop) {
  return luke[prop];
}

var isJedi = getProp('jedi');

So I define a generic function like bellow

function getProp(obj, prop) {
   if (obj.hasOwnProperty(prop)) {
       return obj[prop];
   } else {
       var msg = prop + ' is not a property of the object' + 
                 'you are trying to access';
       throw Error(msg);
   }
}

and call as

var isJedi = getProp(luke, 'jedi');

What is the performance impact of calling a function to access object property vs just assigning it in a variable where needed?

Upvotes: 1

Views: 50

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

What is the performance impact of calling a function to access object property vs just assigning it in a variable where needed?

In absolute terms, in theory it's huge, because you're doing all of that work calling a function, passing arguments, creating a new execution context, etc., etc.

And yet, when I measured this because I was worried about the impact of using forEach, I found that function calls are really really fast, even on the slowest JavaScript engine I could find at the time (JScript in IE6). And modern engines are much faster than IE6's JScript.

My larger concern wouldn't be performance, but rather:

  1. The affect on code readability and,

  2. (For the specific getProp you've shown), the fact that you're disabling one of the key features of JavaScript: The prototype chain (by requiring the property to be an "own" property)

More on readability:

It's common to need to access a nested object hierarchy, such as:

var n = obj.foo.thingies.length;

Consider what that would look like with getProp:

var n = getProp(getProp(getProp(obj, "foo"), "thingies"), "length");

That's, frankly, nearly unreadable.

Barring a really good solid reason to do that, I would just use properties in the normal way.

Upvotes: 4

Related Questions