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年軟件開(kāi)發(fā)和IT教學(xué)經(jīng)驗(yàn)。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項(xiàng)目經(jīng)理、高級(jí)軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
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();//預(yù)先初始化,應(yīng)用啟動(dòng)前或確保在getServiceTypeName服務(wù)調(diào)用前已經(jīng)被初始化完成。
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