Bug Tracker

Opened 8 years ago

Closed 8 years ago

#11463 closed bug (invalid)

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.

Change History (1)

comment:1 Changed 8 years ago by addyosmani

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.

Note: See TracTickets for help on using tickets.