• 美团、饿了么外卖点菜界面联动菜单性能优化


    1. 业务逻辑描述

    业务逻辑描述

    2. 优化后的性能提升对比

    相当明显

    性能分析对比

    3. 常规处理逻辑

    业务逻辑描述

    把左侧菜单的一项成为分类(category),
    把右侧每一项称为(item)。

    1. DOM更新后,获取整个content的高度(包裹所有item的盒子的高度);
    2. 获取每个category在content上的高度,从而获取跳转y值区间数组jumpArr
    3. 在content上监听滑动事件,判断当前y值在jumpArr中的位置,更新左侧category样式。

    这种方法处理的问题(性能上的)

    每次触发scroll事件后都会遍历数组jumpArr来判断此刻左侧导航该有的样式。scroll事件的触发是相当密集的,也就是jumpArr的遍历也是相当密集。对性能有很大的影响。特别是当应用越来越大时、设备比较老旧时。

    4. 我的优化思路

    1. 标题2中的1、2步保持不变,通过相同的方法获得jumpArr;
    2. 上面步骤3采用的是实时遍历,现在抛弃这种做法。而是,生产一个跳转函数,可以使用if...else也可以使用switch...case,这里选用后者,因为性能更加出众。
      注:生成的jumpFunc是字符串,需要使用eval()来进行函数转换。

    5. 代码示例(vue)

    1. 计算获取jumpArr
    getGoodsHeight() {
        //这两项是用来获取content总高的
        const specials = document.querySelector(".specials");
        const itemList = document.querySelectorAll(".group-item");
        //预赛了
        let heightList = [];
        heightList.push(specials.offsetHeight);
        itemList.forEach((element, index) => {
        const eleHeight = element.offsetHeight;
        const preheight = heightList[index];
        heightList.push(preheight + eleHeight);
        });
        this.heightList = heightList;
    }
    
    1. 根据jumpArr得出用于逻辑处理的跳转函数jumpFunc
    getJumpFunc() {
        //这样的写法有助于性能,使用判断而不是用循环
        let i = 0;
        let func = `(function () { return function (y, context) {`;
        const length = this.heightList.length;
        while (i < length) {
            const current = this.heightList[i - 1] || 0;
            const next = this.heightList[i];
            const lastIndex = length - 1;
            let partition = "";
            switch (i) {
                case 0:
                partition = `if(y > 0 && y< ${next}) { context.addNavStyle(${i}) }`;
                break;
                case lastIndex:
                partition = `else { context.addNavStyle(${i}) }};})();`;
                break;
                default:
                partition = `else if (y > ${current} && y <${next}) { context.addNavStyle(${i}) }`;
                break;
            }
            func += partition;
            i++;
        }
        return eval(func);
    },
    
    1. 项目地址

    美团项目

  • 相关阅读:
    SQL Server 性能优化之——T-SQL TVF和标量函数
    SQL Server 性能优化之——T-SQL 临时表、表变量、UNION
    Posix消息队列实现机制
    进程间通信基础知识整理
    进程间通信——FIFO(多个客户进程,一个服务进程)
    VMware+CentOS7+jdk1.7+hadoop2.4.1
    Java并发编程
    java并发编程
    读书笔记——Java IO
    读书笔记——异常
  • 原文地址:https://www.cnblogs.com/looyulong/p/10316724.html
Copyright © 2020-2023  润新知