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: |
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
Fix #13075. Optimize $.type by preferring
typeof
. Close gh-1089.Also fixes browsers where
typeof RegExp === "function"
.Changeset: 5eec75e582d27e2d4f625f6be33eabad84f16239