Bug Tracker

Modify

Ticket #13075 (closed feature: fixed)

Opened 16 months ago

Last modified 16 months ago

Performance optimization for $.type

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

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

comment:1 Changed 16 months ago by Sebi Burkhard

  • Status changed from new to closed
  • Resolution set to fixed

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

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

Changeset: 5eec75e582d27e2d4f625f6be33eabad84f16239

comment:2 Changed 16 months ago by dmethvin

  • Priority changed from undecided to low
  • Type changed from bug to feature
  • Component changed from unfiled to core
  • Milestone changed from None to 1.9

Please follow the  bug reporting guidlines and use  jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

View

Add a comment

Modify Ticket

Action
as closed
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.