简体   繁体   English

ES6 将可迭代转换为数组时间复杂度

[英]ES6 Convert iterable to array time complexity

Im wondering whats the time complexity of turning iterables for example MapIterator into an array.我想知道将可迭代对象(例如 MapIterator)转换为数组的时间复杂度是多少。 lets say I have this code:假设我有这个代码:

    const Component = ({ map }) => {
           return (
        <Fragment>
            {Array.from(map.values()).map(item => <div key={item.key}>{item.name}</div>)}
       </Fragment>
     )
}

what is the time complexity for each Array.from(), is it what Im thinking O(n) or is it because its an MapIterator somehow converted from arraylike to array quicker.每个 Array.from() 的时间复杂度是多少,是我在想 O(n) 还是因为它的 MapIterator 以某种方式更快地从数组转换为数组。

My use case is that I want to save items (which need to be accessed) as a map for performance issues, but I have to run through them as an array.我的用例是我想将项目(需要访问)保存为性能问题的映射,但我必须将它们作为数组运行。

for this questions purpose I can save in state or use selectors or stuff like that对于这个问题,我可以保存状态或使用选择器或类似的东西

what do you guys think?你们有什么感想?

You are correct that Array.from() is O(n).你说Array.from()是 O(n) 是正确的。 If you're concerned about performance, the easiest thing you can do to improve is to not iterate the values twice .如果您担心性能,那么您可以做的最简单的改进就是不要将值迭代两次 Array.from() already accepts a map function as a second optional argument: Array.from()已经接受一个map函数作为第二个可选参数:

Array.from(map.values(), ({ key, name }) => <div key={key}>{name}</div>)

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

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