0

I have incoming tree-like data and I need to transform it into something slightly different. I created a class method:

normalizeMyStuff(data) {
  return data.map(item => {
     //do this..
     //do that..
     const children = item.children ? this.normalizeMyStuff(item.children) : undefined
     return {
       ...some properties,
       children,
     }
  })
}

But with huge amount of data, when this method runs, it freezes my browser for a few seconds. This is not the experience I want to provide. What could I do to optimize it?

12
  • Before anything else, is async an option for you? Commented Sep 15, 2020 at 15:34
  • Just how big is this data? How many nodes in your tree, approximately? Commented Sep 15, 2020 at 15:35
  • @melancia I'm presuming that "transforming" is CPU bound, therefore async won't do anything Commented Sep 15, 2020 at 15:36
  • @Liam good point. Commented Sep 15, 2020 at 15:38
  • @Liam: an async queue of work to be performed longside code to stitch the results together can alleviate such situations by regularly freeing the event loop to do other things. But these days, with worker threads available, I wouldn't bother trying to write that fairly sophisticated code. Commented Sep 15, 2020 at 15:42

1 Answer 1

4

One option would be to start a separate worker thread when the response comes in: send the payload to the worker, do the heavy computational-intensive transformation there, then have the worker send the result back to the main page.

Workers operate in a different environment than their original page, so even if the worker runs an extremely expensive process (like while(true);), the original page will remain pretty responsive; scrolling and button clicks will still be possible while the worker is running.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.