0

I'm building various d3.js dashboards which frequently refer to a javascript_properties.js file which includes properties such as:

var all_charts = (function() {

   return {
     width:860,
     height:500,
     from_date:"",
     to_date:"",
     highlight_color:"#00FFFF"
   }

}());

I use these properties frequently within various functions.

My question is:

Is there any harm in calling each property direct every time I use it or would it be more efficient to declare a local variable at the beginning of each function if a property is going to be called more than once?

To show an example. A local variable:

 var width = all_charts.width;

OR calling

all_charts.width 

as many times as required during a function.

There may be little discernible difference?

1
  • 1
    Make your code readable and don't worry about it, the effect is nonexistent related to the cost of other logic. Commented Sep 13, 2017 at 8:39

1 Answer 1

3

This isn't about memory usage, it's about lookup time.

Yes, caching the property to a local variable may make it faster when using that repeatedly afterward, as the JavaScript engine doesn't have to traverse the scope chain up to the global level to find all_charts and then look up width on it.

But, it's unlikely to make a noticeable difference unless you're using these properties hundreds of thousands of times in the same function.


Side note: There's no point to the function in the all_charts code, what you have does exactly what this does, just more indirectly:

var all_charts = {
  width:860,
  height:500,
  from_date:"",
  to_date:"",
  highlight_color:"#00FFFF"
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.