Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is type conversion faster for Objects or Primitives in Javascript?

Tags:

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.

like image 897
Jason Avatar asked Jan 10 '13 23:01

Jason


1 Answers

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.

like image 172
Bergi Avatar answered Sep 24 '22 03:09

Bergi