4
\$\begingroup\$

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

Speed Test

How can I improve its performance?

\$\endgroup\$
  • \$\begingroup\$ 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? \$\endgroup\$ – elclanrs Mar 20 '14 at 12:40
  • \$\begingroup\$ Your test case seems completely wrong, basically you are measuring the speed of creating the function, not executing it.. \$\endgroup\$ – konijn Mar 20 '14 at 12:41
  • \$\begingroup\$ @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? \$\endgroup\$ – Progo Mar 20 '14 at 12:41
  • \$\begingroup\$ @konijn I am pretty sure that jsperf.com puts inputs into the functions. I'll change my test just in case. \$\endgroup\$ – Progo Mar 20 '14 at 12:43
  • \$\begingroup\$ @konijn I think I have a more accurate test now. \$\endgroup\$ – Progo Mar 20 '14 at 12:53
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Shouldn't the type of "o" be "object"? \$\endgroup\$ – Kevindra Mar 20 '14 at 20:36
  • \$\begingroup\$ Is this quicker that other jQuery/MooTools/My original function? \$\endgroup\$ – Progo Mar 20 '14 at 21:17
  • \$\begingroup\$ 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. \$\endgroup\$ – konijn Mar 20 '14 at 22:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.