返回文章列表

加速PowerShell启动:懒加载

如果你的 Windows Terminal 启动时感觉卡顿,很可能是由于同步初始化了重量级 CLI 工具。通过将这些工具的加载策略改为懒加载(Lazy Loading),可以将配置文件加载时间从 140ms 降低到 20ms 以下。

powershell
# 1. BusyBox(Linux 命令)- 快速直接
if (Get-Command busybox -ErrorAction SilentlyContinue) {
    # 移除 PowerShell 默认的 ls 别名,使用 BusyBox 版本
    if (Get-Alias ls -ErrorAction SilentlyContinue) { Remove-Item Alias:ls -Force }
    
    # 映射 Linux 函数(2>$null 用于压制 Windows 特有的 'nul' 路径错误)
    function ls   { busybox ls --color=auto $args 2>$null }
    function ll   { busybox ls -lh $args 2>$null }
    function grep { busybox grep --color=auto $args }
}

# 2. Starship 提示符 - 懒加载
# 这将延迟执行直到终端窗口已可见
$staticPrompt = {
    # 仅在渲染第一个提示符时初始化 Starship
    Invoke-Expression (&starship init powershell)
    
    # 立即执行新生成的 Starship 提示符
    & $function:prompt
}
Set-Item -Path function:prompt -Value $staticPrompt

性能对比

以下数据使用 Measure-Command { . $PROFILE } 在标准开发机上测得。

指标同步初始化(标准)懒加载(优化后)提升
配置文件加载时间140.47 ms16.49 ms~8.5x 更快
视觉延迟明显卡顿窗口瞬间弹出显著
进程开销高(启动时阻塞)零(延迟到第一次空闲)-

原理说明

  • 消除可执行文件调用: 直接在配置文件中定义 function 比每次搜索 .exe 文件快微秒级别

  • 延迟 I/O: starship init 会生成数千行脚本。将其移出同步启动序列,允许终端 UI 在"重活"开始之前完成渲染

powershellwindows