Skip to content

Commit f06f110

Browse files
committed
perf(core): getType uses a cache for well known types.
getType is called a lot, and it just run the same regexp over and over on the same base types. A cache increase its own efficiency by more than 80% for basic types. On a real world application with a lot of components, getType was profiled for 8% of call duration before this patch, and about 0.5% after. The impact is more limited for smaller applications.
1 parent 8d3fce0 commit f06f110

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/core/util/props.js

+18-1
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,28 @@ const functionTypeCheckRE = /^\s*function (\w+)/
187187
* because a simple equality check will fail when running
188188
* across different vms / iframes.
189189
*/
190-
function getType (fn) {
190+
function getTypeName (fn) {
191191
const match = fn && fn.toString().match(functionTypeCheckRE)
192192
return match ? match[1] : ''
193193
}
194194

195+
/**
196+
* Build a cache for known types.
197+
* We could build it dynamically, but since array are sometime requested,
198+
* it fill up the cache for nothing.
199+
* Type list is taken from https://vuejs.org/v2/guide/components-props.html#Type-Checks
200+
*/
201+
const TYPE_CACHE = new Map(
202+
[String, Number, Boolean, Array, Object, Date, Function, Symbol, null, undefined].map(fn => [fn, getTypeName(fn)]))
203+
204+
function getType (fn) {
205+
const cached = TYPE_CACHE.get(fn)
206+
if (cached !== undefined) {
207+
return cached
208+
}
209+
return getTypeName(fn)
210+
}
211+
195212
function isSameType (a, b) {
196213
return getType(a) === getType(b)
197214
}

0 commit comments

Comments
 (0)