2

Could someone please compare and contrast between the costs of creating objects in JavaScript/JQuery and a simple variable declaration?

For Example:

var G = {}
G.obj = (function(){
        var x = 10; //'private' attribute, can be accessed internally only
        G.y   = 20; //'public'  property
        });

x obviously has a local scope where as Y would be accessible publicly through G with a selector. Are there any significant overheads involved in the latter approach?

Thanks.

Edit: I realize this might sound like a silly question but I am planning an architecture for an HTML5 game, I have to keep little things like these in mind as I move forward.

3
  • If you plan on giving me negative feedback I would at least appreciate the courtesy of a small comment explaining what's what. Commented Jul 7, 2012 at 20:22
  • 1
    I really, really suggest reading this answer to the more-o-less similar question (which is quite easily found by search, btw) - especially the 'premature optimization' part. Commented Jul 7, 2012 at 22:18
  • Hi, thanks for linking me; I wouldn't have posted my question had I found the answer in my search. I try doing my research before bothering people here. Thanks anyway. Commented Jul 8, 2012 at 6:46

1 Answer 1

3

First, you are not really executing the function in your code block.

G.obj = (function(){
    var x = 10; //'private' attribute, can be accessed internally only
    G.y   = 20; //'public'  property
    })();

Now, As far as cost of creating local variables v/s global properties is concerned, AFAIK, accessing(getting/setting) a global property would be slightly more expensive as you are traversing up the scope chain. The higher the property in scope chain, the more the cost. However, this is less of an issue IMHO.

The bigger issue is your choice of sticking things in a global store. Using local variables is helpful as local variables dont stick around after the function finishes execution. Therefore, you dont keep unnecessary state in memory. This IMO should drive your design on where to keep state for your application.

Sign up to request clarification or add additional context in comments.

2 Comments

Appreciate the input. Designing a big app in JavaScript is a little different from what I am used to with regular programming languages such as C++ where global variables are frowned upon. But I can appreciate their existence in this context.

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.