In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use JavaScript's Map to improve performance". In daily operation, I believe many people have doubts about how to use JavaScript's Map to improve performance. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to use JavaScript's Map to improve performance". Next, please follow the editor to study!
What is the difference between Map and regular objects
There are two main differences between Map and regular objects.
1. Unlimited key (Key)
The key of a regular JavaScript object must be String or Symbol, as the following object illustrates:
Const symbol = Symbol (); const string2 = 'string2';const regularObject = {string1:' value1', [string2]: 'value2', [symbol]:' value3'}
By contrast, Map allows you to use functions, objects, and other simple types (including NaN) as keys, as shown in the following code:
Const func = () = > null;const object = {}; const array = []; const bool = false;const map = new Map (); map.set (func, 'value1'); map.set (object,' value2'); map.set (array, 'value3'); map.set (bool,' value4'); map.set (NaN, 'value5')
This feature provides great flexibility when linking different data types.
two。 Traversing directly
In regular objects, in order to traverse keys, values, and entries, you must convert them to arrays, such as using Object.keys (), Object.values (), and Object.entries (), or using for. In loop, because regular objects cannot be traversed directly, and for. The in loop has some limitations: it only traverses enumerable properties, non-Symbol properties, and traverses in an arbitrary order.
Map can be traversed directly, and because it is a keyed collection, the traversal order is the same as the order in which the key values are inserted. You can use for... Of loop or forEach method to traverse the entries of Map, as shown in the following code:
For (let [key, value] of map) {console.log (key); console.log (value);}; map.forEach ((key, value) = > {console.log (key); console.log (value);})
Another benefit is that you can call the map.size property to get the number of keys, while for regular objects, you must first convert to an array and then get the array length, such as: Object.keys ({}). Length.
What is the difference between Map and Set
The behavior of Map is very similar to that of Set, and they both contain some of the same methods, including has, get, set, delete. Both of them are keyed collections, which means you can use methods like forEach to traverse elements in order of insert key values.
The biggest difference is that Map appears in pairs with key/value, just as you can convert an array to Set, or you can convert a two-dimensional array to Map:
Const set = new Set ([1,2,3,4]); const map = new Map ([['one', 1], [' two', 2], ['three', 3], [' four', 4]])
Type conversion
To switch Map back to an array, you can use the structural syntax of ES6:
Const map = new Map ([['one', 1], [' two', 2]]); const arr = [... map]
So far, converting Map to and from regular objects is still not very convenient, so you may need to rely on a functional method, as follows:
Const mapToObj = map = > {const obj = {}; map.forEach ((key, value) = > {obj [key] = value}); return obj;}; const objToMap = obj = > {const map = new Map (); Object.keys (obj) .forEach (key = > {map.set (key, obj [key])}); return map;}
But now, in the first demonstration of ES2019 in August, we saw that Object introduced two new methods: Object.entries () and Object.fromEntries (), which can make the above method much simpler:
Const obj2 = Object.fromEntries (map); const map2 = new Map (Object.entries (obj))
Before you use Object.fromEntries to convert map to object, make sure that the key of map produces a unique result when converting to a string, otherwise you are at risk of data loss.
Performance testing
To prepare for the test, I will create an object and a map, both of which have 1000000 identical key values.
Let obj = {}, map = new Map (), n = 1000000 for (let I = 0; I)
< n; i++) { obj[i] = i; map.set(i, i);} 然后我使用console.time()来衡量测试,由于我特定的系统和Node.js版本的原因,时间精度可能会有波动。测试结果展示了使用Map的性能收益,尤其是添加和删除键值的时。 查询 let result;console.time('Object');result = obj.hasOwnProperty('999999');console.timeEnd('Object');// Object: 0.250msconsole.time('Map');result = map.has(999999);console.timeEnd('Map');// Map: 0.095ms (2.6 times faster) 添加 console.time('Object');obj[n] = n;console.timeEnd('Object');// Object: 0.229msconsole.time('Map');map.set(n, n);console.timeEnd('Map');// Map: 0.005ms (45.8 times faster!) 删除 console.time('Object');delete obj[n];console.timeEnd('Object');// Object: 0.376msconsole.time('Map');map.delete(n);console.timeEnd('Map');// Map: 0.012ms (31 times faster!) Map在什么情况下更慢 在测试中,我发现一种情况常规对象的性能更好:使用for循环去创建常规对象和map。这个结果着实令人震惊,但是没有for循环,map添加属性的性能胜过常规对象。 console.time('Object');for (let i = 0; i < n; i++) { obj[i] = i;}console.timeEnd('Object');// Object: 32.143mslet obj = {}, map = new Map(), n = 1000000;console.time('Map');for (let i = 0; i < n; i++) { map.set(i, i);}console.timeEnd('Map');// Map: 163.828ms (5 times slower) 举个例子 最后,让我们看一个Map比常规对象更合适的例子,比如说我们想写一个函数去检查2个字符串是否由相同的字符串随机排序。 console.log(isAnagram('anagram', 'gramana')); // Should return trueconsole.log(isAnagram('anagram', 'margnna')); // Should return false 有许多方法可以做到,但是这里,map可以帮忙我们创建一个最简单、最快速的解决方案: const isAnagram = (str1, str2) =>{if (str1.length! = = str2.length) {return false;} const map = new Map (); for (let char of str1) {const count = map.has (char)? Map.get (char) + 1: 1; map.set (char, count);} for (let char of str2) {if (! map.has (char)) {return false;} const count = map.get (char)-1; if (count = = 0) {map.delete (char); continue;} map.set (char, count);} return map.size = 0;}
In this example, map is more appropriate than object when it comes to dynamically adding and deleting key values and cannot confirm the data structure (or the number of key values) in advance.
At this point, the study on "how to use JavaScript's Map to improve performance" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.