3

Im wondering whats the time complexity of turning iterables for example MapIterator into an array. 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.

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?

1
  • If you are concerned about performance, the best is to never convert anything to arrays, just process data as iterables, applying all processing logic right to the iterables. Here's one library that can handle that - iter-ops. Commented Dec 14, 2021 at 11:26

1 Answer 1

1

You are correct that Array.from() is 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.values(), ({ key, name }) => <div key={key}>{name}</div>)
Sign up to request clarification or add additional context in comments.

2 Comments

I had no idea this was a valid syntax. reading the docs I see the mapFn, cool!. so converting iterables to array has to be O(n) like i thought huh? This actually solved my particular issue since I Have to map the values, so I already have to spend O(n).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.