Skip to content

Commit

Permalink
perf: reduce duplicate rendering in localSearch (#3170)
Browse files Browse the repository at this point in the history
Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
  • Loading branch information
zonemeen and brc-dd committed Nov 5, 2023
1 parent 37e4ab9 commit 878f437
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/client/theme-default/components/VPLocalSearchBox.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import type { ModalTranslations } from '../../../../types/local-search'
import { pathToFile } from '../../app/utils'
import { useData } from '../composables/data'
import { LRUCache } from '../support/lru'
import { createTranslate } from '../support/translation'
const emit = defineEmits<{
Expand Down Expand Up @@ -142,6 +143,8 @@ const mark = computedAsync(async () => {
return markRaw(new Mark(resultsEl.value))
}, null)
const cache = new LRUCache<string, Map<string, string>>(16) // 16 files
debouncedWatch(
() => [searchIndex.value, filterText.value, showDetailedList.value] as const,
async ([index, filterTextValue, showDetailedListValue], old, onCleanup) => {
Expand All @@ -163,13 +166,12 @@ debouncedWatch(
? await Promise.all(results.value.map((r) => fetchExcerpt(r.id)))
: []
if (canceled) return
const c = new Map<string, Map<string, string>>()
for (const { id, mod } of mods) {
const mapId = id.slice(0, id.indexOf('#'))
let map = c.get(mapId)
let map = cache.get(mapId)
if (map) continue
map = new Map()
c.set(mapId, map)
cache.set(mapId, map)
const comp = mod.default ?? mod
if (comp?.render || comp?.setup) {
const app = createApp(comp)
Expand Down Expand Up @@ -209,7 +211,7 @@ debouncedWatch(
results.value = results.value.map((r) => {
const [id, anchor] = r.id.split('#')
const map = c.get(id)
const map = cache.get(id)
const text = map?.get(anchor) ?? ''
for (const term in r.match) {
terms.add(term)
Expand Down
33 changes: 33 additions & 0 deletions src/client/theme-default/support/lru.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// adapted from https://stackoverflow.com/a/46432113/11613622

export class LRUCache<K, V> {
private max: number
private cache: Map<K, V>

constructor(max: number = 10) {
this.max = max
this.cache = new Map<K, V>()
}

get(key: K): V | undefined {
let item = this.cache.get(key)
if (item !== undefined) {
// refresh key
this.cache.delete(key)
this.cache.set(key, item)
}
return item
}

set(key: K, val: V): void {
// refresh key
if (this.cache.has(key)) this.cache.delete(key)
// evict oldest
else if (this.cache.size === this.max) this.cache.delete(this.first()!)
this.cache.set(key, val)
}

first(): K | undefined {
return this.cache.keys().next().value
}
}

0 comments on commit 878f437

Please sign in to comment.