Skip to content

Commit be5dec0

Browse files
authored
feat(performance): getRectByTaro 方法在小程序内增加缓存以提升性能 (#2831)
* feat: getRectByTaro 方法在小程序内增加缓存以提升性能 * feat: lock 文件提交 * feat: 工具类新增 lru * feat: 增加capacity 参数值校验 * feat: lock 文件还原
1 parent 9cfb6e9 commit be5dec0

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/utils/get-rect-by-taro.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { createSelectorQuery } from '@tarojs/taro'
2+
import MiniLru from '@/utils/lru'
23
import { getRect, inBrowser } from './use-client-rect'
34

5+
const lru = new MiniLru(10)
6+
47
export interface Rect {
58
dataset: Record<string, any>
69
id: string
@@ -30,10 +33,17 @@ export const getRectByTaro = async (element: any): Promise<Rect> => {
3033
}
3134
// 小程序下的逻辑
3235
return new Promise((resolve, reject) => {
36+
if (lru.has(element)) {
37+
resolve(lru.get(element) as Rect)
38+
return
39+
}
3340
createSelectorQuery()
3441
.select(`#${element.uid}`)
3542
.boundingClientRect()
3643
.exec(([rects]) => {
44+
if (rects) {
45+
lru.set(element, rects)
46+
}
3747
resolve(rects)
3848
})
3949
})

src/utils/lru.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
export default class MiniLru {
2+
private cache: Map<any, any>
3+
4+
private capacity: number
5+
6+
constructor(capacity: number) {
7+
if (capacity <= 0) {
8+
throw new Error('Cache capacity must be a positive number')
9+
}
10+
this.cache = new Map()
11+
this.capacity = capacity
12+
}
13+
14+
get(key: any): any | null {
15+
if (this.cache.has(key)) {
16+
const value = this.cache.get(key)
17+
this.cache.delete(key)
18+
this.cache.set(key, value)
19+
return value
20+
}
21+
return null
22+
}
23+
24+
set(key: any, value: any): void {
25+
if (this.cache.has(key)) {
26+
this.cache.delete(key)
27+
} else if (this.cache.size >= this.capacity) {
28+
this.cache.delete(this.cache.keys().next().value)
29+
}
30+
this.cache.set(key, value)
31+
}
32+
33+
has(key: any): boolean {
34+
return this.cache.has(key)
35+
}
36+
}

0 commit comments

Comments
 (0)