《60天AI学习计划启动 | Day 37: AI 聊天性能优化(大量消息 & 流式渲染》

Day 37:AI 聊天性能优化(大量消息 & 流式渲染)

学习目标

  • 识别 聊天页面性能瓶颈(大量 DOM / 频繁 setState)
  • 掌握 “只渲染最近 N 条消息”与简单虚拟化思路
  • 会实现 流式输出的前端节流,减少重渲染次数

核心知识点

  • 性能瓶颈来源

    • 消息越来越多:messages.length → 上千,每次 setState 全量 diff
    • 流式输出:每个 chunk 都触发一次 render,频率过高
    • Markdown/高亮渲染开销大
  • 优化思路

    • 列表截断/虚拟化:只渲染最近 N 条(例如 100 条)+ 提供“展开历史”按钮
    • 流式节流:AI streaming 时先写入 buffer,每隔 50–100ms 合并一次更新
    • 避免全局重渲染:消息列表和输入区拆组件,列表用 React.memo

实战作业(附代码)

  • 作业 1:只渲染最近 N 条消息的列表组件
type Msg = { id:string; role:'user'|'assistant'; content:string }

interface RecentMessagesProps {
  messages: Msg[]
  maxCount?: number
}

export const RecentMessagesList: React.FC<RecentMessagesProps> = ({
  messages,
  maxCount = 100
}) => {
  const visible = messages.length > maxCount
    ? messages.slice(messages.length - maxCount)
    : messages

  return (
    <div style={{ overflowY:'auto', height:400 }}>
      {messages.length > maxCount && (
        <div style={{ color:'#999', fontSize:12 }}>
          仅显示最近 {maxCount} 条消息(共 {messages.length} 条)
        </div>
      )}
      {visible.map(m => (
        <div key={m.id} className={`msg ${m.role}`}>
          {m.content}
        </div>
      ))}
    </div>
  )
}
  • 作业 2:简单节流 hook,用于流式内容合并更新
import { useRef, useState, useEffect } from 'react'

export function useThrottledText(interval = 80) {
  const [text,setText] = useState('')
  const bufRef = useRef('')
  const timerRef = useRef<number | null>(null)

  const append = (chunk:string) => {
    bufRef.current += chunk
    if (timerRef.current == null) {
      timerRef.current = window.setTimeout(() => {
        setText(prev => prev + bufRef.current)
        bufRef.current = ''
        timerRef.current = null
      }, interval)
    }
  }

  useEffect(() => () => {
    if (timerRef.current != null) clearTimeout(timerRef.current)
  }, [])

  return { text, append, reset: () => { setText(''); bufRef.current = '' } }
}

流式时用 append(chunk) 替代直接 setState(content),显著减少 render 次数。


明日学习计划预告(Day 38)

  • 主题:多会话 & 多 Tab 同步
  • 方向
    • 会话列表管理(新建/重命名/归档)
    • 使用 localStorage + storage 事件 做多 Tab 状态同步
posted @ 2025-12-17 10:37  XiaoZhengTou  阅读(1)  评论(0)    收藏  举报