Jason
Jason

Reputation: 2364

Is type conversion faster for Objects or Primitives in Javascript?

Given these two examples:

var myNumber = 10; //primitive

and

var myNumber = new Number(10); //object

Which performs faster when a type conversion occurs?

var myString = myNumber.toString(); //convert to string

I assume that object type conversion is faster since the primitive gets converted to an object to respond to the expression and then back to primitive again.

Upvotes: 7

Views: 227

Answers (2)

Bergi
Bergi

Reputation: 664327

I will summarize the excellent comments to an answer. Thanks to theSystem, RocketHazmat, pst, bfavaretto and Pointy!

Which performs faster? I assume…

You can only test, test, test. jsPerf is a good choice to do that. Tests show that primitive values concatenated with empty string are by far the fastest method - function calls are costly. This holds especially true if the variables are not cached but instantiated each time (test by Geuis).

object type conversion is faster since the primitive gets converted to an object to respond to the expression and then back to primitive again

This is only what the EcmaScript specification describes for behaviour (section 8.7.1, section 9.8), not what current engines do. They will not create any object overhead, but use the internal primitive values only. Do not trust the number of steps in the spec!

However, not calling the Number.prototype.toString function (section 15.7.4.2) - even if it is native - but getting directly to ToString via the addition operator (section 11.6.1 step 7) will be faster.

In general, do not try to prematurely optimize but only when you really get performance problems (you hardly will from this code). So use primitive values for simplicity, and either .toString() or +"" depending on what you find easier to read.

Upvotes: 1

Geuis
Geuis

Reputation: 42267

Primitive number with type casting is the fastest of all.

http://jsperf.com/num-type-conversion

Upvotes: 1

Related Questions