Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perf: reuse Shiki highlighters per theme/lang #3130

Merged
merged 2 commits into from
Apr 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/eleven-guests-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Updates `<Code />` component to cache and reuse Shiki highlighters
2 changes: 1 addition & 1 deletion packages/astro/components/Code.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
import type * as shiki from 'shiki';
import { getHighlighter } from 'shiki';
import { getHighlighter } from './Shiki.js';

export interface Props {
/** The code to highlight. Required. */
Expand Down
22 changes: 22 additions & 0 deletions packages/astro/components/Shiki.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getHighlighter as getShikiHighlighter } from 'shiki';

// Caches Promise<Highligher> for reuse when the same theme and langs are provided
const _resolvedHighlighters = new Map();

function stringify(opts) {
// Always sort keys before stringifying to make sure objects match regardless of parameter ordering
return JSON.stringify(opts, Object.keys(opts).sort());
}

export function getHighlighter(opts) {
const key = stringify(opts);

// Highlighter has already been requested, reuse the same instance
if (_resolvedHighlighters.has(key)) { return _resolvedHighlighters.get(key) }

// Start the async getHighlighter call and cache the Promise
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did a bit more poking around and confirmed that this looks like the memory issue was just due to pages being built in parallel. Each page initialized a highlighter and Node couldn't garbage collect them in between page builds

Caching the promise here makes sure that each page gets an immediate response and they can all share the same highlighter instance

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah nice, we had to do this in the remark plugin also, wish we could reuse more logic between teh two!

const highlighter = getShikiHighlighter(opts);
_resolvedHighlighters.set(key, highlighter);

return highlighter;
}