2

I'm getting response from this provider where there is a huge, deep array.

I only have to loop through this array and do some simple calculation but it's taking quite long to process.

What's the best practice to do this with JavaScript?

3
  • Is that calculation always done on elements at a certain depth, or the depth varies? Commented Dec 9, 2015 at 2:23
  • @HunanRostomyan it's done at a certain depth; say 4. Commented Dec 9, 2015 at 2:24
  • Then loop the array for 4 times... use some counter; initialize it on the startup and then decrease it to 0 from 4. Commented Dec 10, 2015 at 18:29

2 Answers 2

1

The best way to do heavy computation is to start a WebWorker. Remember that transferring large objects to a worker is slow, so you would probably like to get the response (like start an ajax) in the worker itself.

If you are stuck to one thread, you can use the following method to split the computation into smaller parts, but this will not help you if a single iteration takes too long.

function eachAsync(array, fn) {
  return new Promise(function(resolve, reject) {
    var index = 0;
    function chunk() {
      try {
        var end = performance.now() + 20;
        for(;;) {
          if (index < array.length) {
            var current = index++;
            fn(array[current], current);
          } else {
            resolve();
            break;
          }
          if (performance.now() >= end) {
            schedule();
            break;
          }
        }
      } catch(e) {
        reject(e);
      }
    }
    function schedule() {
      setTimeout(chunk, 10);
    }
    schedule();
  });
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using HTML5 with a modern browser you can use WebWorkers: http://ejohn.org/blog/web-workers/

Or you can use a homegrown method: Execute Background Task In Javascript

4 Comments

Since it is tagged with node.js I believe there are more threading options for OP.
@SteveWellens what is the most popular option for node.js? From what i found, node-webworker-threads performance doesn't seem very impressive in their example.
@TuanAnhTran I don't know what the most popular option is. If they are a bit slow...who cares: they are in a background thread.
@SteveWellens if they are in background it does not mean they can run slowly.

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.