Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

You Don't Know JS: Async and Performance - cooperative concurrency?

Kyle example is about chunking data (when is so big) by asynchronous events and make events interleave in the event loop queue, that part i couldn't get:

The example from book:

var res = [];
// `response(..)` receives array of results from the Ajax call
function response(data) {

   var chunk = data.splice( 0, 1000 );

   res = res.concat(

    chunk.map( function(val){
      return val * 2;
    } )
  );

  if (data.length > 0) {

    setTimeout( function(){
        response( data );
    }, 0 );
  }
}
// ajax(..) is some arbitrary Ajax function given by a library
ajax( "http://some.url.1", response );
ajax( "http://some.url.2", response );

I could not get that part, my mind can not accept that this could make code perform better, wouldn't that cause data from two arrays to interleave, or i just don't understand how event loop work??

like image 298
Saher Elgendy Avatar asked Oct 15 '22 09:10

Saher Elgendy


1 Answers

It appears that you are correct that there is a potential for misordering of data with multiple ajax calls (and it was very astute of you to notice, +1), with the code posted you could get:

  1. ajax call 1 starts
  2. ajax call 1 finishes
  3. append the first 1000 elements from call 1
  4. ajax call 2 starts
  5. append the next 1000 elements from call 1
  6. ajax call 2 finishes
  7. append the first 1000 elements from call 2
  8. append the next 1000 elements from call 1

As for the performance aspect of the question, remember that 'performance' isn't just one thing. If by performance you mean 'how long does this block of code take to run' then chunking will lead to worse performance. But this is frontend. 'Performance' is really about user experience, and your Javascript code runs on the main thread. If you have a 10 second operation then your UI is unresponsive for 10 seconds. If you chunk it then the user can still interact with the page while it's running, even if it takes a little longer to complete.

like image 76
Jared Smith Avatar answered Nov 15 '22 06:11

Jared Smith