JavaScript系列(54)--性能优化技术详解

JavaScript性能优化技术详解 ⚡

今天,让我们继续深入研究JavaScript的性能优化技术。掌握这些技术对于构建高性能的JavaScript应用至关重要。

性能优化基础概念 🎯

💡 小知识:JavaScript性能优化涉及多个方面,包括代码执行效率、内存使用、DOM操作、网络请求等。通过合理的优化策略,可以显著提升应用的响应速度和用户体验。

性能分析工具实现 📊

// 1. 性能计时器
class PerformanceTimer {
    constructor() {
        this.marks = new Map();
        this.measures = new Map();
    }
    
    mark(name) {
        this.marks.set(name, performance.now());
    }
    
    measure(name, startMark, endMark) {
        const startTime = this.marks.get(startMark);
        const endTime = this.marks.get(endMark);
        
        if (startTime && endTime) {
            const duration = endTime - startTime;
            this.measures.set(name, duration);
            return duration;
        }
        
        return null;
    }
    
    getMeasure(name) {
        return this.measures.get(name);
    }
    
    clearMarks() {
        this.marks.clear();
    }
    
    clearMeasures() {
        this.measures.clear();
    }
}

// 2. 代码性能分析器
class CodeProfiler {
    constructor() {
        this.profiles = new Map();
    }
    
    startProfile(name) {
        const startTime = performance.now();
        const startMemory = performance.memory?.usedJSHeapSize;
        
        this.profiles.set(name, {
            startTime,
            startMemory,
            calls: 0,
            totalTime: 0,
            maxTime: 0
        });
    }
    
    endProfile(name) {
        const profile = this.profiles.get(name);
        if (!profile) return;
        
        const endTime = performance.now();
        const endMemory = performance.memory?.usedJSHeapSize;
        
        const duration = endTime - profile.startTime;
        const memoryDiff = endMemory - profile.startMemory;
        
        profile.calls++;
        profile.totalTime += duration;
        profile.maxTime = Math.max(profile.maxTime, duration);
        profile.lastMemoryImpact = memoryDiff;
    }
    
    getProfile(name) {
        const profile = this.profiles.get(name);
        if (!profile) return null;
        
        return {
            ...profile,
            averageTime: profile.totalTime / profile.calls
        };
    }
    
    getAllProfiles() {
        const results = {};
        for (const [name, profile] of this.profiles) {
            results[name] = this.getProfile(name);
        }
        return results;
    }
}

// 3. 函数执行时间分析装饰器
function profileExecution(target, propertyKey, descriptor) {
    const originalMethod = descriptor.value;
    const profiler = new CodeProfiler();
    
    descriptor.value = function(...args) {
        profiler.startProfile(propertyKey);
        const result = originalMethod.apply(this, args);
        profiler.endProfile(propertyKey);
        
        console.log(`Function ${propertyKey} profile:`, profiler.getProfile(propertyKey));
        return result;
    };
    
    return descriptor;
}

代码优化技术 💻

// 1. 循环优化
class LoopOptimizer {
    // 优化数组遍历
    static optimizedForEach(array, callback) {
        const length = array.length;
        for (let i = 0; i < length; i++) {
            callback(array[i], i);
        }
    }
    
    // 分块处理大数组
    static *chunkedProcess(array, chunkSize = 1000) {
        const length = array.length;
        for (let i = 0; i < length; i += chunkSize) {
            yield array.slice(i, Math.min(i + chunkSize, length));
        }
    }
    
    // 使用Web Worker处理耗时操作
    static createWorkerProcess(workerFunction) {
        const blob = new Blob([`(${workerFunction.toString()})()`], 
            { type: 'application/javascript' });
        return new Worker(URL.createObjectURL(blob));
    }
}

// 2. 函数优化
class FunctionOptimizer {
    constructor() {
        this.cache = new Map();
    }
    
    // 函数记忆化
    memoize(fn) {
        return (...args) => {
            const key = JSON.stringify(args);
            if (this.cache.has(key)) {
                return this.cache.get(key);
            }
            
            const result = fn.apply(this, args);
            this.cache.set(key, result);
            return result;
        };
    }
    
    // 函数防抖
    debounce(fn, delay) {
        let timeoutId;
        return (...args) => {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => fn.apply(this, args), delay);
        };
    }
    
    // 函数节流
    throttle(fn, limit) {
        let inThrottle;
        return (...args) => {
            if (!inThrottle) {
                fn.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
}

// 3. DOM优化
class DOMOptimizer {
    constructor() {
        this.mutationObserver = null;
        this.virtualDOM = new Map();
    }
    
    // 批量DOM更新
    batchUpdate(updates) {
        const fragment = document.createDocumentFragment();
        
        updates.forEach(update => {
            const element = this.createElement(update);
            fragment.appendChild(element);
        });
        
        document.body.appendChild(fragment);
    }
    
    // 虚拟DOM实现
    createElement(vnode) {
        if (typeof vnode === 'string') {
            return document.createTextNode(vnode);
        }
        
        const element = document.createElement(vnode.tag);
        
        for (const [key, value] of Object.entries(vnode.props || {})) {
            element.setAttribute(key, value);
        }
        
        (vnode.children || []).forEach(child => {
            element.appendChild(this.createElement(child));
        });
        
        return element;
    }
    
    // DOM变更监控
    observeChanges(target, callback) {
        this.mutationObserver = new MutationObserver(callback);
        this.mutationObserver.observe(target, {
            childList: true,
            subtree: true,
            attributes: true
        });
    }
}

高级优化模式 🚀

// 1. 虚拟滚动实现
class VirtualScroller {
    constructor(container, items, itemHeight) {
        this.container = container;
        this.items = items;
        this.itemHeight = itemHeight;
        this.visibleItems = new Map();
        this.scrollTop = 0;
        
        this.container.style.overflow = 'auto';
        this.container.style.position = 'relative';
        
        this.init();
    }
    
    init() {
        // 设置容器高度
        this.container.style.height = `${this.items.length * this.itemHeight}px`;
        
        // 监听滚动事件
        this.container.addEventListener('scroll', this.onScroll.bind(this));
        
        // 初始渲染
        this.render();
    }
    
    onScroll() {
        this.scrollTop = this.container.scrollTop;
        this.render();
    }
    
    render() {
        const startIndex = Math.floor(this.scrollTop / this.itemHeight);
        const endIndex = Math.min(
            startIndex + Math.ceil(this.container.clientHeight / this.itemHeight),
            this.items.length
        );
        
        // 移除不可见项
        for (const [index, element] of this.visibleItems) {
            if (index < startIndex || index >= endIndex) {
                element.remove();
                this.visibleItems.delete(index);
            }
        }
        
        // 添加可见项
        for (let i = startIndex; i < endIndex; i++) {
            if (!this.visibleItems.has(i)) {
                const element = this.createItem(i);
                this.container.appendChild(element);
                this.visibleItems.set(i, element);
            }
        }
    }
    
    createItem(index) {
        const element = document.createElement('div');
        element.style.position = 'absolute';
        element.style.top = `${index * this.itemHeight}px`;
        element.style.height = `${this.itemHeight}px`;
        element.textContent = this.items[index];
        return element;
    }
}

// 2. 资源预加载器
class ResourcePreloader {
    constructor() {
        this.cache = new Map();
        this.loading = new Set();
    }
    
    preload(resources) {
        resources.forEach(resource => {
            if (!this.cache.has(resource) && !this.loading.has(resource)) {
                this.loading.add(resource);
                
                const promise = this.loadResource(resource)
                    .then(result => {
                        this.cache.set(resource, result);
                        this.loading.delete(resource);
                    })
                    .catch(error => {
                        console.error(`Failed to preload ${resource}:`, error);
                        this.loading.delete(resource);
                    });
                
                return promise;
            }
        });
    }
    
    loadResource(resource) {
        if (resource.endsWith('.js')) {
            return this.loadScript(resource);
        } else if (resource.endsWith('.css')) {
            return this.loadStyle(resource);
        } else if (/\.(png|jpg|gif|svg)$/.test(resource)) {
            return this.loadImage(resource);
        }
        
        return Promise.reject(new Error('Unsupported resource type'));
    }
    
    loadScript(url) {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = url;
            script.onload = () => resolve(script);
            script.onerror = reject;
            document.head.appendChild(script);
        });
    }
    
    loadStyle(url) {
        return new Promise((resolve, reject) => {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = url;
            link.onload = () => resolve(link);
            link.onerror = reject;
            document.head.appendChild(link);
        });
    }
    
    loadImage(url) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.src = url;
            img.onload = () => resolve(img);
            img.onerror = reject;
        });
    }
}

// 3. Web Worker任务管理器
class WorkerTaskManager {
    constructor(workerScript) {
        this.worker = new Worker(workerScript);
        this.taskQueue = new Map();
        this.taskId = 0;
        
        this.worker.onmessage = this.handleMessage.bind(this);
        this.worker.onerror = this.handleError.bind(this);
    }
    
    executeTask(task, data) {
        return new Promise((resolve, reject) => {
            const id = this.taskId++;
            
            this.taskQueue.set(id, { resolve, reject });
            
            this.worker.postMessage({
                id,
                task,
                data
            });
        });
    }
    
    handleMessage(event) {
        const { id, result, error } = event.data;
        const task = this.taskQueue.get(id);
        
        if (task) {
            if (error) {
                task.reject(error);
            } else {
                task.resolve(result);
            }
            
            this.taskQueue.delete(id);
        }
    }
    
    handleError(error) {
        console.error('Worker error:', error);
    }
    
    terminate() {
        this.worker.terminate();
        this.taskQueue.clear();
    }
}

最佳实践建议 💡

  1. 性能监控模式
// 1. 性能监控器
class PerformanceMonitor {
    constructor() {
        this.metrics = new Map();
        this.thresholds = new Map();
    }
    
    setThreshold(metric, value) {
        this.thresholds.set(metric, value);
    }
    
    recordMetric(metric, value) {
        if (!this.metrics.has(metric)) {
            this.metrics.set(metric, []);
        }
        
        const values = this.metrics.get(metric);
        values.push({
            value,
            timestamp: Date.now()
        });
        
        // 保持最近100个记录
        if (values.length > 100) {
            values.shift();
        }
        
        // 检查是否超过阈值
        const threshold = this.thresholds.get(metric);
        if (threshold && value > threshold) {
            this.handleThresholdExceeded(metric, value, threshold);
        }
    }
    
    getMetricStats(metric) {
        const values = this.metrics.get(metric);
        if (!values || values.length === 0) {
            return null;
        }
        
        const numbers = values.map(v => v.value);
        return {
            average: numbers.reduce((a, b) => a + b) / numbers.length,
            max: Math.max(...numbers),
            min: Math.min(...numbers),
            current: numbers[numbers.length - 1]
        };
    }
    
    handleThresholdExceeded(metric, value, threshold) {
        console.warn(`Performance threshold exceeded for ${metric}:`, {
            value,
            threshold,
            stats: this.getMetricStats(metric)
        });
    }
}

// 2. 性能优化建议生成器
class PerformanceAdvisor {
    constructor() {
        this.rules = new Map();
        this.initializeRules();
    }
    
    initializeRules() {
        this.addRule('longTask', metrics => {
            if (metrics.taskDuration > 50) {
                return {
                    severity: 'warning',
                    message: '检测到长任务,考虑使用Web Worker或任务分割'
                };
            }
        });
        
        this.addRule('memoryLeak', metrics => {
            if (metrics.memoryGrowth > 10000000) { // 10MB
                return {
                    severity: 'error',
                    message: '检测到可能的内存泄漏'
                };
            }
        });
        
        this.addRule('domSize', metrics => {
            if (metrics.domNodes > 1000) {
                return {
                    severity: 'warning',
                    message: 'DOM节点数量过多,考虑使用虚拟滚动或延迟加载'
                };
            }
        });
    }
    
    addRule(name, checkFn) {
        this.rules.set(name, checkFn);
    }
    
    analyze(metrics) {
        const issues = [];
        
        for (const [name, checkFn] of this.rules) {
            const result = checkFn(metrics);
            if (result) {
                issues.push({
                    rule: name,
                    ...result
                });
            }
        }
        
        return issues;
    }
}

// 3. 性能报告生成器
class PerformanceReporter {
    constructor() {
        this.monitor = new PerformanceMonitor();
        this.advisor = new PerformanceAdvisor();
    }
    
    generateReport() {
        const metrics = {
            taskDuration: this.monitor.getMetricStats('taskDuration'),
            memoryGrowth: this.monitor.getMetricStats('memoryGrowth'),
            domNodes: this.monitor.getMetricStats('domNodes'),
            fps: this.monitor.getMetricStats('fps')
        };
        
        const issues = this.advisor.analyze(metrics);
        
        return {
            timestamp: Date.now(),
            metrics,
            issues,
            recommendations: this.generateRecommendations(issues)
        };
    }
    
    generateRecommendations(issues) {
        const recommendations = new Set();
        
        issues.forEach(issue => {
            switch (issue.rule) {
                case 'longTask':
                    recommendations.add('考虑使用Web Worker处理耗时任务');
                    recommendations.add('实现任务分割和调度');
                    break;
                case 'memoryLeak':
                    recommendations.add('检查闭包和事件监听器');
                    recommendations.add('使用WeakMap/WeakSet存储对象引用');
                    break;
                case 'domSize':
                    recommendations.add('实现虚拟滚动');
                    recommendations.add('使用文档片段批量更新DOM');
                    break;
            }
        });
        
        return Array.from(recommendations);
    }
}

结语 📝

JavaScript性能优化是一个持续的过程,需要从多个维度进行考虑和实践。通过本文,我们学习了:

  1. 性能分析工具的实现
  2. 代码优化技术
  3. 高级优化模式
  4. 性能监控和优化建议
  5. 最佳实践和设计模式

💡 学习建议:在实际开发中,要根据具体场景选择合适的优化策略。性能优化不是一蹴而就的,需要持续监控和改进。同时,过度优化可能会带来代码可维护性的问题,要在性能和可维护性之间找到平衡。


如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇

终身学习,共同成长。

咱们下一期见

💻

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/963383.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

word2vec 实战应用介绍

Word2Vec 是一种由 Google 在 2013 年推出的重要词嵌入模型,通过将单词映射为低维向量,实现了对自然语言处理任务的高效支持。其核心思想是利用深度学习技术,通过训练大量文本数据,将单词表示为稠密的向量形式,从而捕捉单词之间的语义和语法关系。以下是关于 Word2Vec 实战…

数据库安全管理中的权限控制:保护数据资产的关键措施

title: 数据库安全管理中的权限控制:保护数据资产的关键措施 date: 2025/2/2 updated: 2025/2/2 author: cmdragon excerpt: 在信息化迅速发展的今天,数据库作为关键的数据存储和管理中心,已经成为了企业营运和决策的核心所在。然而,伴随着数据规模的不断扩大和数据价值…

【漫话机器学习系列】076.合页损失函数(Hinge Loss)

Hinge Loss损失函数 Hinge Loss&#xff08;合页损失&#xff09;&#xff0c;也叫做合页损失函数&#xff0c;广泛用于支持向量机&#xff08;SVM&#xff09;等分类模型的训练过程中。它主要用于二分类问题&#xff0c;尤其是支持向量机中的优化目标函数。 定义与公式 对于…

openmv的端口被拆分为两个 导致电脑无法访问openmv文件系统解决办法 openmv USB功能改动 openmv驱动被更改如何修复

我之前误打误撞遇到一次&#xff0c;直接把openmv的全部端口删除卸载然后重新插上就会自动重新装上一个openmv端口修复成功&#xff0c;大家可以先试试不行再用下面的方法 全部卸载再重新插拔openmv 要解决OpenMV IDE中出现的两个端口问题&#xff0c;可以尝试以下步骤&#x…

洛谷P1403 [AHOI2005] 约数研究

题目链接&#xff1a;P1403 [AHOI2005] 约数研究 - 洛谷 | 计算机科学教育新生态 题目难度&#xff1a;普及一 题目分析&#xff1a;本题很明显是要你求从i到n的质因数个数之和&#xff0c;如果采用暴力肯定是超时的&#xff0c;故我的想法是采用埃氏筛法来求时间复杂度为&…

elasticsearch8.15 高可用集群搭建(含认证Kibana)

文章目录 1.资源配置2.系统参数优化3.JDK17安装4.下载&安装ES 8.155.生成ES的证书(用于ES节点之间进行安全数据传输)6.修改ES 相关配置文件7.创建es用户并启动8.配置ES的账号和密码(用于ES服务端和客户端)9.下载和安装Kibana10.编辑Kibana配置文件11.启动Kiabana12.访问Kia…

MATLAB中的IIR滤波器设计

在数字信号处理中&#xff0c;滤波器是消除噪声、提取特征或调整信号频率的核心工具。其中&#xff0c;无限脉冲响应&#xff08;IIR&#xff09;滤波器因其低阶数实现陡峭滚降的特性&#xff0c;被广泛应用于音频处理、通信系统和生物医学工程等领域。借助MATLAB强大的工具箱&…

数据结构:优先级队列—堆

一、优先级队列 1、优先级队列概念 优先级队列&#xff0c;听名字我们就知道他是一种队列&#xff0c;队列在前面我们已经学习过了&#xff0c;它是一种先进先出的数据结构&#xff0c;但是在特殊的情况下&#xff0c;我们我们队列中元素是带有一定优先级的&#xff0c;它需要…

北大:三阶段学习优化多模态推理问答

&#x1f4d6;标题&#xff1a;ReasVQA: Advancing VideoQA with Imperfect Reasoning Process &#x1f310;来源&#xff1a;arXiv, 2501.13536 &#x1f31f;摘要 &#x1f538;视频问答&#xff08;VideoQA&#xff09;是一项具有挑战性的任务&#xff0c;需要理解视频中…

从零开始:用Qt开发一个功能强大的文本编辑器——WPS项目全解析

文章目录 引言项目功能介绍1. **文件操作**2. **文本编辑功能**3. **撤销与重做**4. **剪切、复制与粘贴**5. **文本查找与替换**6. **打印功能**7. **打印预览**8. **设置字体颜色**9. **设置字号**10. **设置字体**11. **左对齐**12. **右对齐**13. **居中对齐**14. **两侧对…

Jason配置环境变量

jason官网 https://jason-lang.github.io/ https://github.com/jason-lang/jason/releases 步骤 安装 Java 21 或更高版本 安装 Visual Studio Code 根据操作系统&#xff0c;请按照以下具体步骤操作 视窗 下载 Jason 的最新版本&#xff0c;选择“jason-bin-3.3.0.zip”…

机器学习--概览

一、机器学习基础概念 1. 定义 机器学习&#xff08;Machine Learning, ML&#xff09;&#xff1a;通过算法让计算机从数据中自动学习规律&#xff0c;并利用学习到的模型进行预测或决策&#xff0c;而无需显式编程。 2. 与编程的区别 传统编程机器学习输入&#xff1a;规…

如何使用SliverGrid组件

文章目录 1 概念介绍2 使用方法3 示例代码 我们在上一章回中介绍了SliverList组件相关的内容&#xff0c;本章回中将介绍SliverGrid组件.闲话休提&#xff0c;让我们一起Talk Flutter吧。 1 概念介绍 我们在本章回中介绍的SliverGrid组件是一种网格类组件&#xff0c;主要用来…

大模型培训讲师老师叶梓分享:DeepSeek多模态大模型janus初探

以下视频内容为叶梓分享DeepSeek多模态大模型janus的部署&#xff0c;并验证其实际效果&#xff0c;包括图生文和文生图两部分。 叶梓老师人工智能培训分享DeepSeek多模态大模型janus初探 DeepSeek 的多模态大模型 Janus 是一款强大的 AI 模型&#xff0c;专注于图像和文本的多…

一文掌握ADB的安装及使用

文章目录 一、什么是ADB&#xff1f;二、 安装ADB2.1 下载ADB2.2 配置环境变量 三、连接Android设备四、 常用ADB命令五、ADB高级功能5.1 屏幕截图和录制5.2 模拟按键输入5.3 文件管理5.4 系统设置管理5.5 系统操作指令5.6 日志操作指令5.7 APK操作指令5.8 设备重启和恢复 六、…

【机器学习与数据挖掘实战】案例11:基于灰色预测和SVR的企业所得税预测分析

【作者主页】Francek Chen 【专栏介绍】 ⌈ ⌈ ⌈机器学习与数据挖掘实战 ⌋ ⌋ ⌋ 机器学习是人工智能的一个分支,专注于让计算机系统通过数据学习和改进。它利用统计和计算方法,使模型能够从数据中自动提取特征并做出预测或决策。数据挖掘则是从大型数据集中发现模式、关联…

bat脚本实现自动化漏洞挖掘

bat脚本 BAT脚本是一种批处理文件&#xff0c;可以在Windows操作系统中自动执行一系列命令。它们可以简化许多日常任务&#xff0c;如文件操作、系统配置等。 bat脚本执行命令 echo off#下面写要执行的命令 httpx 自动存活探测 echo off httpx.exe -l url.txt -o 0.txt nu…

Kafka下载

一、Kafka下载 下载地址&#xff1a;https://kafka.apache.org/downloads 二、Kafka安装 因为选择下载的是 .zip 文件&#xff0c;直接跳过安装&#xff0c;一步到位。 选择在任一磁盘创建空文件夹&#xff08;不要使用中文路径&#xff09;&#xff0c;解压之后把文件夹内容…

学习日记-250202

现在开始要继续写我的日记了......&#xff08;也可以当作笔记吧&#xff09; 一.论文 Prompt Transfer for Dual-Aspect Cross Domain Cognitive Diagnosis 主要内容&#xff1a; 主要是加入prompt提示&#xff0c; 为重叠实体设计个性化的提示&#xff0c;为非重叠实体设计共…

【人工智能学习笔记 一】 AI分层架构、基本概念分类与产品技术架构

新的一年2025要对AI以及LLM有个强化的学习&#xff0c;所以第一篇先对整体有个大概的认知&#xff0c;一直分不清LLM和AI的关系&#xff0c;在整个体系里的位置&#xff0c;以及AIGC是什么东西&#xff0c;AI AGENT类似豆包等和大语言模型的具体关系是什么&#xff0c;整个AI的…