Reputation: 484
I'm trying to understand how Javascript works. Profiling some code, I've found that declarations in a "typed" oriented way are slower than declarations that not are "typed". Of course, I know that JS is not a typed language.
I've tested this on Firefox, Chrome and Opera, always with same results.
var repetitions = 10000000;
console.time("a");
for (var i=0; i<repetitions; i++) {
var a = "...";
}
console.timeEnd("a");
console.time("b");
for (var i=0; i<repetitions; i++) {
var b = new String("...");
}
console.timeEnd("b")
Upvotes: 0
Views: 60
Reputation: 214949
In V8 specifically, if you inspect the generated bytecode (node --print-bytecode
), you'll get something like this:
> return "..."
LdaConstant [0]
Return
> return new String("...")
LdaGlobal [0], [0]
Star r0
LdaConstant [1]
Star r1
Ldar r0
Construct r0, r1-r1, [2]
Return
which basically means that a string literal just loads the pointer from the constants pool, while new String
involves far more steps - load the global String
object, load the constant, invoke the generic Construct
method. I guess things are not much different in FF or any other engine.
Upvotes: 1