stahlhammer
stahlhammer

Reputation: 107

Optimizing recursion

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?

Upvotes: 0

Views: 47

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371193

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.

Upvotes: 4

Related Questions