Bug Tracker

Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#13075 closed feature (fixed)

Performance optimization for $.type

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

Description

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.

http://jsperf.com/jquery-type-with-primitives

http://jsperf.com/jquery-type-with-primitives

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[ core_toString.call(obj) ] || "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: http://rubyjs.org/blog/2012/12/when-to-use-typeof/

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

I accidentally already filed a pull request: https://github.com/jquery/jquery/pull/1089#issuecomment-11494659

Change History (2)

comment:1 Changed 10 years ago by Sebi Burkhard

Resolution: fixed
Status: newclosed

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

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

Changeset: 5eec75e582d27e2d4f625f6be33eabad84f16239

comment:2 Changed 10 years ago by dmethvin

Component: unfiledcore
Milestone: None1.9
Priority: undecidedlow
Type: bugfeature
Note: See TracTickets for help on using tickets.