Skip to content

Commit 2fb6bda

Browse files
its-miromaIMB11
authored andcommitted
perf(md): limit the compile cache's memory usage
add maxSize of 64MB to the markdown compile result LRUCache, such that large pages do not grow this cache unboundedly. change the cache key from JSON.stringify({ src, ts, relativePath }) (which not only included the entire source of each file in each key, but also instantiated an object and called JSON.stringify), to a simpler string concatenation with the sha256 hash of src. Co-authored-by: Calum H. (IMB11) <contact@cal.engineer> Based-on-patch-by: Calum H. (IMB11) <contact@cal.engineer>
1 parent 3fbaf9c commit 2fb6bda

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

src/node/markdownToVue.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { resolveTitleFromToken } from '@mdit-vue/shared'
22
import { LRUCache } from 'lru-cache'
3+
import { hash } from 'node:crypto'
34
import fs from 'node:fs'
45
import path from 'node:path'
56
import { createDebug } from 'obug'
@@ -24,7 +25,12 @@ import { getGitTimestamp } from './utils/getGitTimestamp'
2425
import { processIncludes } from './utils/processIncludes'
2526

2627
const debug = createDebug('vitepress:md')
27-
const cache = new LRUCache<string, MarkdownCompileResult>({ max: 1024 })
28+
const cache = new LRUCache<string, MarkdownCompileResult>({
29+
maxSize: 64 * 1024 * 1024,
30+
sizeCalculation(value, key) {
31+
return Math.max(1, 2 * (key.length + value.vueSrc.length))
32+
}
33+
})
2834

2935
const scriptRE = /<\/script>/
3036
const scriptLangTsRE = /<\s*script[^>]*\blang=['"]ts['"][^>]*/
@@ -51,8 +57,7 @@ export function clearCache(relativePath?: string) {
5157
return
5258
}
5359

54-
relativePath = JSON.stringify({ relativePath }).slice(1)
55-
cache.find((_, key) => key.endsWith(relativePath!) && cache.delete(key))
60+
cache.find((_, key) => key.endsWith(`:${relativePath}`) && cache.delete(key))
5661
}
5762

5863
function normalizeDriveLetter(file: string) {
@@ -122,7 +127,8 @@ export async function createMarkdownToVueRenderFn(
122127
file = rewrites.get(normalizeDriveLetter(file)) || file
123128
const relativePath = slash(path.relative(srcDir, file))
124129

125-
const cacheKey = JSON.stringify({ src, ts, relativePath })
130+
const srcHash = hash('sha256', src, 'base64url')
131+
const cacheKey = `${srcHash}:${ts}:${relativePath}`
126132
if (options.cache !== false) {
127133
const cached = cache.get(cacheKey)
128134
if (cached) {

0 commit comments

Comments
 (0)