In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "what are the differences between Object and Map in JavaScript". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the differences between Object and Map in JavaScript?"
Usage comparison
For Object, the key type can only be a string, number, or Symbol;, while for Map, it can be any type. (including Date,Map, or custom objects)
Elements in Map maintain the order in which they were inserted, while Object does not completely maintain the order in which they were inserted, but is sorted according to the following rules:
Non-negative integers are listed first, and the sort is in numerical order from smallest to largest.
Then all strings, negative integers, and floating-point numbers are listed in the order in which they are inserted.
Finally, it will be listed that Symbol,Symbol is also sorted according to the order in which it is inserted.
Reading the length of Map is simple, you only need to call its .size () method, while reading the length of Object requires additional calculation: Object.keys (obj) .length
Map is an iterable object, so the key-value pairs can be iterated through the for of loop or the .foreach () method, while ordinary object key-value pairs are not iterated by default and can only be accessed through the for in loop (or use Object.keys (o), Object.values (o), Object.entries (o) to get numbers representing keys or values) in the order mentioned above.
Const o = {}; const m = new Map (); o [Symbol.iterator]! = undefined; / / false m [Symbol.iterator]! = undefined; / / true
When a new key is added in Map, the key on its prototype is not overwritten, while when a new key is added in Object, it is possible to overwrite the key on its prototype:
Object.prototype.x = 1; const o = {x const 2}; const m = new Map ([[x Magne2]]); o.x; / 2 Magi x = 1 is covered by m. X; / / 1 Magi x = 1 will not be covered.
JSON supports Object rather than Map by default. If you want to transmit Map over JSON, you need to use the .toJSON () method, and then pass in the recovery function in JSON.parse () to restore it.
JSON will not be expanded here. Interested friends can take a look at this: serialization and parsing of JSON.
Const o = {x const 1}; const m = new Map (['x], 1]]); const o 2 = JSON.parse (JSON.stringify (o)); / / {x v v 1} const m 2 = JSON.parse (JSON.stringify (m)) / / the difference when syntactic contrast is created
Obejct
Const o = {}; / object literals const o = new Object (); / / call constructor const o = Object.create (null); / / call static method Object.create
For Object, we all choose object literals when 95% +, which is not only the easiest to write, but also more efficient in terms of performance than the following function calls. The only possible use for building functions is to explicitly encapsulate a primitive type; Object.create can prototype objects.
Map
Const m = new Map (); / call constructor unlike Object, Map doesn't have so many fancy creation methods, and usually only uses its constructor to create it.
In addition to the above methods, we can also call the constructors of Object and Map or the Object.create () method through the Function.prototype.apply (), Function.prototype.call (), reflect.apply (), and Reflect.construct () methods, so we won't expand here.
Differences when adding / reading / deleting elements
Obejct
Const o = {}; / / add / modify o.x = 1; o ['y'] = 2; / / read o.x; / / 1o ['y']; / / 2 / or use the new conditional attribute access expression of ES2020 to read oint.x; / / 1oroom.['y']; / 2 / / delete delete o.b
For new elements, it seems easier to use the first method, but it also has some limitations:
Attribute names cannot contain spaces and punctuation
Property name cannot start with a number
For more information on conditional attribute access expressions, take a look at this: conditional attribute access expressions
Map
Const m = new Map (); / add / modify m.set ('xboxes, 1); / read map.get (' x'); / / delete map.delete ('b')
For simple additions, deletions, queries and modifications, the method on Map is also very convenient to use, but when performing linkage operations, the usage in Map is slightly bloated:
Const m = new Map ([['xpenalty 1]]); / / if we want to add one to the original value of x, we need to do this: m.set (' x, m.get ('x') + 1); m.get ('x'); / / 2 const o = {x: 1}; / / it will be much easier to modify on the object: o.xportable; o.x / 2 performance comparison
Next, let's discuss the performance of Object and Map. I don't know if you have heard that the performance of Map is better than Object. Anyway, I have seen it many times, and even mentioned the performance advantage of Map over Object in JS elevation 4. However, the summary of performance is very general, so I intend to do some tests to compare the differences between them.
Testing method
All the performance tests I do here are based on the V8 engine. The speed is judged by the performance.now () function that comes with the JS standard library, and the memory usage is checked by the memory in Chrome devtool.
For speed testing, performance.now () often returns 0 because a single operation is too fast. So I did 10000 cycles and judged the time difference. Because the loop itself takes up part of the time, the following tests can only be used as a rough reference.
Performance at creation time
The code for the test is as follows:
Let n, N2 = 5; / / Speed while (n2mura -) {let p1 = performance.now (); n = 10000; while (nmelet -) {let o = {};} let p2 = performance.now (); n = 10000; while (nMub -) {let m = new Map ();} let p3 = performance.now () Console.log (`Object: ${(p2-p1) .tofixed (3)} ms, Map: ${(p3-p2) .tofixed (3)} ms`);} / / memory class Test {} let test = new Test (); test.o = o; test.m = m
The first thing to compare is the performance when creating Object and Map. For the speed created, the performance is as follows:
We can find that creating Object is faster than Map. The memory usage is as follows:
We focus on its Retained Size, which represents the space allocated to it. (that is, the amount of memory released when deleted)
By comparison, we can see that empty Object takes up less inner space than empty Map. So this round of Object won the first round.
Performance when adding elements
The code for the test is as follows:
Console.clear (); let n, N2 = 5; let o = {}, m = new Map (); / / Velocity while (N2 -) {let p1 = performance.now (); n = 10000; while (let -) {o [Math.random ()] = Math.random ();} let p2 = performance.now (); n = 10000; while (n -) {m.set (Math.random (), Math.random ()) } let p3 = performance.now (); console.log (`Object: ${(p2-p1) .tofixed (3)} ms, Map: ${(p3-p2) .tofixed (3)} ms`);} / / memory class Test {} let test = new Test (); test.o = o; test.m = m
The speed when creating a new element is as follows:
We can find that Map is faster than Object when creating new elements. The memory usage is as follows:
By comparison, we can find that when there are a certain number of elements, Object takes up about 78% more memory than Map. I have also tested it many times and found that this percentage is very stable when there are enough elements. So it's more efficient to use Map when a lot of new operations are needed and a lot of data needs to be stored.
Performance when reading elements
The code for the test is as follows:
Let n; let o = {}, m = new Map (); n = 10000; while (Math.random -) {o [Math.random ()] = Math.random ();} n = 10000; while (nmuri -) {m.set (Math.random (), Math.random ());} let p1 = performance.now (); for (key in o) {let k = o [key];} let p2 = performance.now () For ([key] of m) {let k = m.get (key);} let p3 = performance.now (); `Object: ${(p2-p1) .tofixed (3)} ms, Map: ${(p3-p2) .tofixed (3)} ms`
The speed at which elements are read is as follows:
By comparison, we can find that Object has a slight advantage, but the overall difference is not big.
Performance when deleting elements
I don't know if you've ever heard of the low performance of the delete operator, and there are even times when you would rather set the value to undefined rather than use the delete operator for the sake of performance. But under the recent optimization of V8, its efficiency has been improved a lot.
The code for the test is as follows:
Let n; let o = {}, m = new Map (); n = 10000; while (performance.now -) {o [Math.random ()] = Math.random ();} n = 10000; while (nmuri -) {m.set (Math.random (), Math.random ());} let p1 = performance.now (); for (key in o) {delete o [key];} let p2 = performance.now () For ([key] of m) {m.delete (key);} let p3 = performance.now (); `Object: ${(p2-p1) .tofixed (3)} ms, Map: ${(p3-p2) .tofixed (3)} ms`
The speed at which an element is deleted is as follows:
We can find that the speed of Map is slightly higher when doing delete operations, but the overall difference is not that big.
Special circumstances
In fact, in addition to the most basic situation, there is also a special situation. Remember the ordering of keys in Object that we mentioned earlier? We mentioned that the non-negative integers are listed first. In fact, v8 treats non-negative integers as keys differently from other types as keys. Negative integers as part of keys are treated as arrays, that is, non-negative integers are treated as fast arrays when they have a certain degree of continuity, and as slow arrays if they are too sparse.
For fast arrays, it has continuous memory, so it is faster to read and write and takes up less memory. For more information, take a look at this: explore the underlying implementation of "arrays" under the JS V8 engine.
When the key is a continuous non-negative integer, the performance is as follows:
We can see that not only is Object faster on average, but its memory footprint is also greatly reduced.
Thank you for your reading, the above is "what is the difference between Object and Map in JavaScript". After the study of this article, I believe you have a deeper understanding of the difference between Object and Map in JavaScript, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.