javascript - How to choose between using an expression directly and assigning it to a variable? - Stack Overflow

So this is puzzling to me. Are variables expensive?Let's take a look at this code:var div1 = doc

So this is puzzling to me. Are variables expensive? Let's take a look at this code:

var div1 = document.createElement('div');
var div2 = document.createElement('div');

div2.appendChild(div1);

Now this one

var div2 = document.createElement('div');

div2.appendChild(document.createElement('div'));

So, on the second example, I'm doing the same thing as on the first one. Is it more expensive to declare a variable than not? Do I save memory by just creating and using an element on the fly?

EDIT: this is a sample code to illustrate the question. I know that in this specific case, the memory saved (or not) in minimal.

So this is puzzling to me. Are variables expensive? Let's take a look at this code:

var div1 = document.createElement('div');
var div2 = document.createElement('div');

div2.appendChild(div1);

Now this one

var div2 = document.createElement('div');

div2.appendChild(document.createElement('div'));

So, on the second example, I'm doing the same thing as on the first one. Is it more expensive to declare a variable than not? Do I save memory by just creating and using an element on the fly?

EDIT: this is a sample code to illustrate the question. I know that in this specific case, the memory saved (or not) in minimal.

Share Improve this question edited Oct 8, 2024 at 21:56 dumbass 27.3k4 gold badges38 silver badges74 bronze badges asked Jan 7, 2012 at 0:26 pec1985pec1985 1611 silver badge9 bronze badges 2
  • Expense aside, I don't like to create variables that are only used once (that is, assigned a value at declaration and then used in only one other place). Particularly in longer code blocks I find this makes it harder to read because I'm left wondering where else the variable might be used, so for your simple example I'd go with the second version. Having said that, sometimes a one-use variable makes the code easier to read if it saves having a really long line with lots of object.method(otherObject.method()+another.method()) type calls. I guess I'm saying go with the most readable for you. – nnnnnn Commented Jan 7, 2012 at 0:44
  • Slightly off topic, but the way you are building the DOM is actually quite expensive. Although using createElement is the ideal approach, appending html to a container's innerHTML (or using something like JQuery.append) is a lot faster, e.g. document.getElementById('parentId').innerHTML += '<div>blah blah</div>' – tomfumb Commented Jan 7, 2012 at 0:53
Add a ment  | 

3 Answers 3

Reset to default 7

Variables are extremely cheap in JavaScript, yet, no matter how cheap they are, everything has a cost.

Having said that, it's not a noticable difference, and you should be thinking more about making your code readable rather than performing micro-optimizations.

You should be using variables to save repeated operations. In your example above, it's likely you need the variable pointing to the newly created div, or you'll be able to do nothing to it... unless you end up retrieving it from the DOM; which will prove many times more costly than the variable, as DOM manipulation is one of the slowest parts of JavaScript.

In theory, there is a tiny little amount of memory you save by not doing the variable declaration, because a variable declaration requires that the JavaScript engine creates a property on the variable binding object for the execution context in which you declare it. (See the specification, Section 10.5 and associated sections.)

In reality, you will never notice the difference, not even on a (relatively) slow engine like IE's. Feel free to use variables wherever they make the code clearer. Creating a property on a variable binding object (e.g., declaring a variable) is a very, very, very quick operation. (Avoid it at global scope, of course, but not because of memory use.)

Caveat: If the variable refers to a big memory structure that you only hold temporarily, and you create closures within that function context, the big memory structure may (in some engines) be kept in memory longer than necesary. Example:

function foo(element) {
    var a = /* ...create REALLY BIG structure here */;
    element.addEventListener("event", function() {
        // Do something **not** referencing `a` and not doing an `eval`
    }, false);
}

In an unsophisticated engine, since the event handler is a closure over the context of the call to foo, in theory a is available to the handler and so what it references remains "referencible" and not available for garbage collection until/unless that event handler function is no longer referencible. In any decent engine (like the V8 engine in Chrome), because you neither refer to a nor use eval within the closure (event handler), it's fine. If you want to defend yourself from mediocre engines, set a to undefined before foo returns, so the engine (no matter how mediocre) knows that the event handler won't be referencing that structure even if it were to reference a.

Yes, you save memory, no it is in no way an amount that matters.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744689025a4588094.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信