# Improving the performance of my “type” function

I'm writing a JavaScript library, and I am using this function for type detection:

function type(obj){
return  Object.prototype.toString.call(obj).replace(/([]|object|\s)/gi, "");
}


Their works ok, but compared to jQuery and MooTools it stinks.

http://jsperf.com/code-type-test-a-test

How can I improve its performance?

• This is micro-optimization, don't worry about it. 7,767,355 ops/sec in FF is more than enough. How often do you check the type of something anyway? – elclanrs Mar 20 '14 at 12:40
• Your test case seems completely wrong, basically you are measuring the speed of creating the function, not executing it.. – konijn Mar 20 '14 at 12:41
• @elclanrs You are right. But if I have functions in my library that are slower than functions in other libraries, then wouldn't you use the faster library? – Progo Mar 20 '14 at 12:41
• @konijn I am pretty sure that jsperf.com puts inputs into the functions. I'll change my test just in case. – Progo Mar 20 '14 at 12:43
• @konijn I think I have a more accurate test now. – Progo Mar 20 '14 at 12:53

Interesting question, since there is only 1 line to review and a limited amount of ways to get the 'type of an object

I will say that

function type(obj){
return  Object.prototype.toString.call(obj).replace(/([]|object|\s)/gi, "");
}
var o = new (function Name(){})();
console.log( type(o) );


returns ""

whereas

function type(o){
return  o !== undefined && o.constructor ? o.constructor.name : "Undefined";
}
var o = new (function Name(){})();
console.log( type(o) );
`

returns "Name" which is more correct.

It seems ( though I fudged it a little, a re-test is required ) that the second approach can be faster on IE and Safari ). All in all, I would copy the jQuery source, it takes care of all corner cases and is sufficiently fast.

• Shouldn't the type of "o" be "object"? – Kevindra Mar 20 '14 at 20:36
• Is this quicker that other jQuery/MooTools/My original function? – Progo Mar 20 '14 at 21:17
• Progo, that's how it looks like for IE/Safari, it is slowest on Chrome though. @Kevindra, no, the name of the constructor is the name of the type. – konijn Mar 20 '14 at 22:16