Skip to main content

Bug Tracker

Side navigation

#11463 closed bug (invalid)

Opened March 11, 2012 09:17AM UTC

Closed March 11, 2012 12:15PM UTC

Use instanceof instead of toString

Reported by: bobef Owned by:
Priority: low Milestone: None
Component: unfiled Version: 1.7.1
Keywords: Cc:
Blocked by: Blocking:
Description

JavaScript has instanceof operator, which is way faster for determining the type of a variable than converting the variable to string and comparing strings. And unfortunately the latter is what jquery is using. In my benchmarks it is more than 30x faster to use instanceof rather than toString. It is true that this 30x in this case can not make a difference for a script that is executed several (thousand) times, but there are two reasons to fix this. 1) jquery is widely used worldwide, which means this is wasting millions of millions of CPU cycles worldwide as we speak and degrading the web perfomance worldwide. 2) as jquery is reputable library and many people are using it as an example and learning from it, it is setting very bad example and driving developers' skills down worldwide. I've wrote an article with benchmarks for the benefits of using instanceof http://bobef.net/articles/proper-type-determination-in-javascript . Regards.

Attachments (0)
Change History (1)

Changed March 11, 2012 12:15PM UTC by addyosmani comment:1

priority: undecidedlow
resolution: → invalid
status: newclosed

Whilst there are situations where instanceof may indeed appear to perform better, it isn't anywhere near as reliable as say a Object.prototype.toString.call(o) check when it comes to type checking.

If scripting in multi-frame DOM environments, objects created within one iframe don't necessarily share the prototype with those created within another iframe. Because their constructors are different objects, instanceof will fail in those instances and so has limited reliability.

Also see here http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ where John Resig (in the comments) points out that for this very reason jQuery stopped using instanceof all the way back in version 1.3.