]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
perf: cache string helpers
authorEvan You <yyx990803@gmail.com>
Mon, 16 Dec 2019 18:06:43 +0000 (13:06 -0500)
committerEvan You <yyx990803@gmail.com>
Tue, 17 Dec 2019 17:31:38 +0000 (12:31 -0500)
packages/shared/src/index.ts

index 137f38fe732f69d0de071fae85455db81ecd10a4..de6596198e75d3e1fbdee0d1f8ff4c247e9c3423 100644 (file)
@@ -66,19 +66,33 @@ export const isReservedProp = /*#__PURE__*/ makeMap(
     'onVnodeBeforeUnmount,onVnodeUnmounted'
 )
 
-const camelizeRE = /-(\w)/g
-export const camelize = (str: string): string => {
-  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
+function cacheStringFunction<T extends (str: string) => string>(fn: T): T {
+  const cache: Record<string, string> = Object.create(null)
+  return ((str: string) => {
+    const hit = cache[str]
+    return hit || (cache[str] = fn(str))
+  }) as any
 }
 
+const camelizeRE = /-(\w)/g
+export const camelize = cacheStringFunction(
+  (str: string): string => {
+    return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
+  }
+)
+
 const hyphenateRE = /\B([A-Z])/g
-export const hyphenate = (str: string): string => {
-  return str.replace(hyphenateRE, '-$1').toLowerCase()
-}
+export const hyphenate = cacheStringFunction(
+  (str: string): string => {
+    return str.replace(hyphenateRE, '-$1').toLowerCase()
+  }
+)
 
-export const capitalize = (str: string): string => {
-  return str.charAt(0).toUpperCase() + str.slice(1)
-}
+export const capitalize = cacheStringFunction(
+  (str: string): string => {
+    return str.charAt(0).toUpperCase() + str.slice(1)
+  }
+)
 
 // compare whether a value has changed, accounting for NaN.
 export const hasChanged = (value: any, oldValue: any): boolean =>