Skip to main content

Bug Tracker

Side navigation

#13075 closed feature (fixed)

Opened December 18, 2012 05:04PM UTC

Closed December 23, 2012 08:45PM UTC

Last modified January 08, 2013 11:53PM UTC

Performance optimization for $.type

Reported by: hasclass Owned by:
Priority: low Milestone: 1.9
Component: core Version: git
Keywords: Cc:
Blocked by: Blocking:

I optimized $.type( obj ) when obj is a primitive. This speeds up that method by a magnitude ( 100x for chrome) without sacrificing performance when obj is not a primitive.

The trick is to check first using typeof (which is extremely fast) whether an object is a primitive or not. obj is a primitive if it isnt typeof 'object'. For primitives avoid the costly core_toString call which converts a primitive into a wrapper object.

type: function (obj) {
  if ( obj == null ) {
    return false;
  return typeof obj === 'object' ?
    // handles {}, [], new String, new Number, etc.:
    class2type[ ] || "object"  : 
    // handles 1, 'foo', function () {}, true:
    typeof obj;

Passing a wrapper object like new String("foo") will use the normal core_toString.

This technique has a significant performance impact on old and (especially) new browsers. I worte a blog post on this:

Additionally I added 4 tests for $.type to also test wrapper objects.

I accidentally already filed a pull request:

Attachments (0)
Change History (2)

Changed December 23, 2012 08:45PM UTC by Sebi Burkhard comment:1

resolution: → fixed
status: newclosed

Fix #13075. Optimize $.type by preferring typeof. Close gh-1089.

Also fixes browsers where typeof RegExp === "function".

Changeset: 5eec75e582d27e2d4f625f6be33eabad84f16239

Changed January 08, 2013 11:53PM UTC by dmethvin comment:2

component: unfiledcore
milestone: None1.9
priority: undecidedlow
type: bugfeature