获取js函数执行时间的装饰器

获取js函数执行时间的装饰器

业务背景

为了进行代码优化和提升页面性能因此想要了解js函数的执行时间,因此用装饰器开发了这个获取函数执行时间的小工具。

封装的工具

export default function measure(target: any, name: string, descriptor: any) {
  let oldValue = descriptor.value;
  descriptor.value = async function() {
    console.time(name);
    // console.log(this);
    // console.log(arguments);
    // tslint:disable-next-line:no-invalid-this
    let res = await oldValue.apply(this, arguments);
    console.timeEnd(name);
    return res;
  };
}

页面中调用:

export default class Tree extends Vue {
    created() {
        this.init();
    }
  
    init() {
        this.getTreeData('floor');
    }
  
    @Measure // 获取程序执行的时间
    async getTreeData(type: string) {
        if (this.treeConfig.noType) {
            type = '';
        }
        let[err, data] = await this.$to(common.tree({
            data: {
                type,
                cid: this.companyId,
                getDevice: this.treeConfig.getDevice,
                deviceType: this.treeConfig.deviceType,
                getRegion: this.treeConfig.getRegion,
                getMFloor: this.treeConfig.getDeviceFloor,
                getCold: this.treeConfig.getCold
            }
        }));
    }
}