简体   繁体   English

ES6地图迭代成本

[英]ES6 Map iteration cost

I have an array of items: var treeItems = []; 我有一个项目数组: var treeItems = []; . treeItems.length maybe 5-30 (maybe 50), but each treeItem is pretty big object. treeItems.length可能是5到30(也许是50),但是每个treeItem都是很大的对象。 I should do both: iterate through items & get item by id. 我应该同时做:遍历项目并按ID获取项目。

I'm considering to replace array with es6 Map . 我正在考虑用es6 Map替换array。 And to iterate through map use: Array.from(treeItemsMap.values()) operation. 要遍历地图,请使用: Array.from(treeItemsMap.values())操作。

Question: what is the cost (time/memory) of Array.from(map.values()) operation? 问题: Array.from(map.values())操作的成本(时间/内存)是Array.from(map.values())

PS I'm doing SPA for mobile, so memory usage is also significant. PS我正在做移动SPA,因此内存使用也很重要。

The spec says: 规格说明:

Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. 必须使用哈希表或其他机制来实现Map对象,这些机制通常提供的访问时间与集合中元素的数量成线性关系。

The specific cost is implementation dependent. 具体成本取决于实现方式。

Using Array.from will just copy the data into an array, and that wastes memory uselessly. 使用Array.from会将数据复制到一个数组中,这将浪费内存。 Better iterate the map instead. 最好改为迭代地图。

Note 50 items is a very small data. 注意50项是非常小的数据。 I don't think having huge objects in the map matters. 我认为在地图中放置大型物体并不重要。 Remember JS is a pass-by-value language, but in case of objects, that value is a reference. 请记住,JS是一种按值传递的语言,但是对于对象而言,该值是一个引用。 So the map will only contain 50 references to objects, which will be stored separately. 因此,地图将仅包含对对象的50个引用,这些引用将单独存储。 Iterating or accessing that tiny map shouldn't cost much. 迭代或访问该小地图应该不会花费太多。

Approach with .map() iterator. 使用.map()迭代器的方法。

We can use a simple trick for Maps, because there is no such operation for Maps as map(). 我们可以对Maps使用一个简单的技巧,因为对于Maps,没有诸如map()这样的操作。 Suggested by Dr. Axel Rauschmayer : * Convert the map into an array of [key,value] pairs. Axel Rauschmayer博士建议:*将地图转换为[键,值]对数组。 * Map or filter the array. *映射或过滤数组。 * Convert the result back to a map. *将结果转换回地图。

Example: 例:

let map0 = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
]);

const map1 = new Map(
  [...map0]
  .map(([k, v]) => ['_' + k, v * 2])
);

resulted in 导致

{'_a' => 2, '_b' => 4, '_c' => 6}

Approach with for(){...} oprator. for(){...}操作者联系。

We can iterate ES6 Map like this: 我们可以像这样迭代ES6 Map:

let map0 = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
]);

let map1 = new Map();
for (let [key, value] of map0) {
    map1.set('_' + k, v * 2);    
}

resulted in 导致

{'_a' => 2, '_b' => 4, '_c' => 6}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM