背景问题
随着应用复杂度增加,性能问题逐渐显现,需要从多个角度进行优化。
方案思考
- 如何优化渲染性能
- 如何减少内存占用
- 如何优化网络请求
具体实现
防抖节流优化:
// utils/debounce.ts – 防抖节流工具
import { ref, onUnmounted } from 'vue';
// 防抖Hook
export function useDebounce<T extends (…args: any[]) => any>(
fn: T,
delay: number
) {
let timeoutId: NodeJS.Timeout | null = null;
const debouncedFn = (…args: Parameters<T>) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn(…args);
}, delay);
};
// 清理函数
const clear = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
onUnmounted(() => {
clear();
});
return { debouncedFn, clear };
}
// 节流Hook
export function useThrottle<T extends (…args: any[]) => any>(
fn: T,
limit: number
) {
let inThrottle: boolean = false;
const throttledFn = (…args: Parameters<T>) => {
if (!inThrottle) {
fn(…args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
return throttledFn;
}
缓存策略:
// utils/cache.ts – 缓存工具
interface CacheOptions {
maxAge?: number; // 缓存最大存活时间(毫秒)
maxSize?: number; // 最大缓存数量
}
class Cache {
private cache: Map<string, { value: any; timestamp: number }>;
private options: CacheOptions;
constructor(options: CacheOptions = {}) {
this.cache = new Map();
this.options = {
maxAge: 5 * 60 * 1000, // 默认5分钟
maxSize: 100, // 默认最大100条
…options
};
}
// 设置缓存
set(key: string, value: any): void {
// 检查缓存大小
if (this.cache.size >= this.options.maxSize!) {
// 删除最旧的缓存项
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, {
value,
timestamp: Date.now()
});
}
// 获取缓存
get(key: string): any | null {
const item = this.cache.get(key);
if (!item) {
return null;
}
// 检查是否过期
if (this.options.maxAge &&
Date.now() – item.timestamp > this.options.maxAge) {
this.cache.delete(key);
return null;
}
return item.value;
}
// 删除缓存
delete(key: string): boolean {
return this.cache.delete(key);
}
// 清空缓存
clear(): void {
this.cache.clear();
}
// 清理过期缓存
cleanup(): void {
const now = Date.now();
for (const [key, item] of this.cache) {
if (this.options.maxAge &&
now – item.timestamp > this.options.maxAge) {
this.cache.delete(key);
}
}
}
}
// 创建全局缓存实例
export const globalCache = new Cache();
// API缓存装饰器
export function cachedApi<T extends (…args: any[]) => Promise<any>>(
fn: T,
cacheKey: string,
maxAge?: number
): T {
return ((…args: any[]) => {
const key = `${cacheKey}_${JSON.stringify(args)}`;
const cached = globalCache.get(key);
if (cached) {
return Promise.resolve(cached);
}
return fn(…args).then(result => {
globalCache.set(key, result);
return result;
});
}) as T;
}
效果验证
通过这些优化技巧,可以显著提升应用性能,改善用户体验。
经验总结
性能优化是一个持续的过程,需要在开发过程中不断关注和改进。





