In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you about how to use the JavaScript Set collection to write code faster, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
I'm sure there are many developers who insist on using basic global objects: number,string,object,array and Boolean values.
For many use cases, these are what you need. However, if you want to make your code as fast and extensible as possible, these basic types are not always good enough.
There is a lot of overlap between what an array can do and what Set can do. Using Set often brings runtime advantages that arrays cannot achieve. In this article, we will explore how to do this.
How is Set different?
The most fundamental difference is that the array is an index collection, which means that the data values in the array are sorted by the index.
Const arr = [A, B, C, D]; console.log (arr.indexOf (A)); / / Result: 0 console.log (arr.indexOf (C)); / / Result: 2
By contrast, Set is a keyed collection. Instead of using indexes, Set uses keys to sort the data. The elements of Set can be iterated in the order in which they are inserted and cannot contain any duplicate data. In other words, each item in the collection must be unique.
What are the main benefits?
In direct comparison, Set collections have several advantages over arrays, especially in terms of running time:
Search for items: it is slow to use indexOf () or includes () to check whether an item exists in the array.
Delete items: in the Set collection, you can delete items by their value. In an array, equivalents use splice () based on the index of the element. As with the previous point, the speed of relying on indexes is slow.
Insert items: it is faster to add items to Set than to add items to an array using push (), unshift (), or the equivalent.
Save NaN: you cannot use indexOf () or include () to find the value NaN, but Set can store that value.
Delete duplicates: the Set object stores only unique values. This is a significant advantage over arrays where additional code is needed to handle duplicates if you want to avoid storing duplicates.
What is the complexity of time?
The linear time complexity of the method used by the array to search for items is O (N). In other words, the elapsed time increases at the same rate as the data size.
By contrast, the time complexity of Set's methods for searching, deleting, and inserting items is only O (1)-which means that the size of the data actually has nothing to do with the running time of these methods!
How fast is the collection of Set?
Although the running time may vary greatly depending on the system used, the size of the data provided, and other variables, I hope my test results will give you a realistic understanding of the speed of Set. I will share the three simple tests I did and the results I got.
1. Prepare for the test
Before running any tests, let's create an array and a Set, each with a million entries. For simplicity, I'll start at 0 and go all the way to 999999.
Let arr = [], set = new Set (), n = 1000000; for (let I = 0; I
< n; i++) { arr.push(i); set.add(i); } 2. 测试一:搜索项目 首先,让我们搜索数字 123123,我们知道它将返回true。 let result; console.time('Array'); result = arr.indexOf(123123) !== -1; console.timeEnd('Array'); console.time('Set'); result = set.has(123123); console.timeEnd('Set'); 结果:Array: 0.173ms,set: 0.023ms,set的速度快了7.54倍。 3. 测试二:添加项目 现在,让我们向每个集合中添加一个新项目。 console.time('Array'); arr.push(n); console.timeEnd('Array'); console.time('Set'); set.add(n); console.timeEnd('Set'); 结果:Array: 0.018ms,set: 0.003ms,set速度提高了6.73倍。 4. 测试三:删除项目 最后,让我们从每个集合中删除一个项目(我们可以使用刚刚添加的项目)。没有内置的数组方法,因此我们将创建一个辅助函数以保持所有内容的整洁: const deleteFromArr = (arr, item) =>{let index = arr.indexOf (item); return index! =-1 & & arr.splice (index, 1);}
This is the code for the test:
Console.time ('Array'); deleteFromArr (arr, n); console.timeEnd (' Array'); console.time ('Set'); set.delete (n); console.timeEnd (' Set')
The result: Array: 1.122ms Set set: 0.015ms, in this case, the speed of Set is astonishing 74.13 times!
Overall, we can see that using Set instead of arrays can greatly improve the runtime. Now let's look at some practical examples in which the Set collection is useful.
Case 1: remove duplicate values from the array
If you want to quickly remove duplicate values from an array, you can convert them to Set. By far, this is the simplest way to filter unique values:
Const duplicateCollection = ['A','B','C','C','D','B','C']; / / if you want to turn the array into the Set collection let uniqueCollection = new Set (duplicateCollection); console.log (uniqueCollection) / / Result: Set (4) {"A", "B", "C", "D"} / / if you want to keep the values in the array let uniqueCollection = [. New Set (duplicateCollection)] Console.log (uniqueCollection) / / Result: ["A", "B", "C", "D"]
Case 2: a Google interview question
Given an unordered array of integers and a value sum, true is returned if any two items can be added so that they are equal to the value of sum. Otherwise, return false.
Therefore, given an array of [3, 5, 5, 1, 4] and a value of 9, our function should return true, because 4 + 5 = 9.
A good way to solve this problem is to traverse the array while creating a set of Set.
Let's apply this idea to the example above. When we encounter 3, we can add 6 to our Set because we know we need to find a sum of 9. Then, every time we touch a new value in the array, we can check to see if it is in our Set. When we get to 5, we will add 4 to our Set. Then, when we finally encounter 4, we will also find it in our Set, so we can return to true.
The solution might look like this:
Const findSum = (arr, val) = > {let searchValues = new Set (); searchValues.add (val-arr [0]); for (let I = 1, length = arr.length; I
< length; i++) { let searchVal = val - arr[i]; if (searchValues.has(arr[i])) { return true; } else { searchValues.add(searchVal); } }; return false; }; 这是一个更简洁的版本: const findSum = (arr, sum) =>Arr.some ((set = > n = > set.has (n) | |! set.add (sum-n)) (new Set))
Because the time complexity of Set.prototype.has () is only O (1), using Set to store instead of an array can help our overall solution achieve linear run time O (N).
If we instead rely on Array.prototype.indexOf () or Array.prototype.includes (), both of which have a time complexity of O (N), the total elapsed time will be O (N ²), much slower!
If you have never been exposed to JavaScript Set before, I hope I have demonstrated their usefulness!
The above is how to use the JavaScript Set collection to write code more quickly, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.