javascript - performance optimization issues
高洛峰
高洛峰 2017-07-05 10:54:21
0
6
1034


How to optimize this code? The boss said that it should be converted into ES6 map data structure. My conversion may be wrong and it seems to be slower.


This is the optimization I did, it seems to be slower, please give me some advice

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(6)
習慣沉默

Using filter() can indeed be done in one sentence, but it is not very efficient. In fact, you can use find (refer to MDN)

function getServiceTypeName(code) {
    return serviceTypeList.find(val => val.name === code);
}

Unfortunately, IE does not support find(), so there is a Polyfill near the end of the MDN documentation.

If you use map to implement it, you don’t need to use ES6 Map, because the native object supports string type keys, but no matter how it is implemented, the conversion of this map should be done outside getServiceTypeName. Because the conversion process is more time-consuming than what you wrote for ... of.

function toMap(list) {
    return list.reduce((map, item) => {
        map.set(item.name, item);
        return map;
    }, new Map());
}

serviceTypeMap = toMap(serviceTypeList);

function getServiceTypeName(code) {
    return serviceTypeMap.get(code);
}
代言

objToStrMap only needs to be initialized once. You are initializing it every time in the loop, which will be slower.

Additional instructions

const objToStrMap=function (obj) {
    var myMap=new Map();

    obj.forEach(
        (item) => myMap.set(item.typeId, item.name)
    );

    return myMap;
}
var serviceTypeList=[
    {
        'typeId':1,
        'name':'first'
    },
    {
        'typeId':2,
        'name':'second'
    },
]
function init(){

    serviceTypeList= objToStrMap(serviceTypeList)
}
init();//预先初始化,应用启动前或确保在getServiceTypeName服务调用前已经被初始化完成。

getServiceTypeName=function (code) {

    return serviceTypeList.get(code);
}
console.log(getServiceTypeName(2));  //输出:second
为情所困

...

First convert it into a map structure with key-value pairs name:Id. Then you can directly use name to get the corresponding id. You didn't understand the meaning of the method he told you at all.

First convert the type array into a map structure, and then get it through map.get(code). No need to traverse.

阿神

In

function, you can write like this
let result = serviceTypeList.map((val)=> val.typeId === code);
retVal = result.name;

仅有的幸福

Just half a line of code

serviceTypeList.filter(obj => obj.id==*code*)[0].name
女神的闺蜜爱上我

The operation of filtering in a loop is not slow.

What solution to converting to map needs to consider the cost of the conversion itself

The map implementation that comes with some languages ​​uses arrays when the collection is small, eliminating the need for hashcode operations and improving efficiency

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template