Skip to content

perf: lazily initialize Handlebars and SyntaxHighlighter to reduce startup time#2739

Merged
tusharmath merged 2 commits intomainfrom
improve-startup-time
Mar 30, 2026
Merged

perf: lazily initialize Handlebars and SyntaxHighlighter to reduce startup time#2739
tusharmath merged 2 commits intomainfrom
improve-startup-time

Conversation

@tusharmath
Copy link
Copy Markdown
Collaborator

@tusharmath tusharmath commented Mar 30, 2026

Summary

Defer initialization of the Handlebars template engine and syntax highlighter to their first use, reducing application startup time by avoiding expensive upfront work.

Context

ForgeTemplateService and MarkdownFormat previously initialized their heaviest dependencies — the Handlebars engine and the SyntaxHighlighter — eagerly at construction time. These initializations are non-trivial in cost and are not always needed immediately (or at all) during a given session, so paying for them unconditionally at startup was wasteful.

Changes

  • ForgeTemplateService: Replaced the eagerly-initialized Arc<RwLock<Handlebars>> with Arc<OnceCell<RwLock<Handlebars>>>. Added a private get_hb() async helper that creates the Handlebars instance on the first call and returns a reference to it on all subsequent calls. The new() constructor now does no heavy work.
  • MarkdownFormat: Changed the highlighter field from a plain SyntaxHighlighter to a OnceLock<SyntaxHighlighter>. The highlighter is created via get_or_init the first time format() is called, leaving construction of MarkdownFormat itself lightweight.

Key Implementation Details

Both changes use the standard lazy-initialization primitives idiomatic to their execution context:

  • tokio::sync::OnceCell for the async ForgeTemplateService (supports .await in the initializer closure).
  • std::sync::OnceLock for the synchronous MarkdownFormat (no async required).

The public API of both types is unchanged — callers see no difference in behavior.

Testing

# Run template service tests
cargo insta test --accept -p forge_services

# Run display/markdown tests
cargo insta test --accept -p forge_display

# Quick type-check across the workspace
cargo check

Fixes #2574

@tusharmath tusharmath changed the title perf(template): lazily initialize Handlebars in ForgeTemplateService perf: lazily initialize Handlebars and SyntaxHighlighter to reduce startup time Mar 30, 2026
@tusharmath tusharmath merged commit 54fe7a4 into main Mar 30, 2026
12 checks passed
@tusharmath tusharmath deleted the improve-startup-time branch March 30, 2026 09:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance]: Stabilize flaky zsh rprompt CI benchmark

1 participant