0

I'm trying to improve the speed of a JSON parsing script, that creates an HTML file based on data inside of it.

The JSON file has a nested rows/columns/content modules structure, and I loop through them to transform every content module to HTML.

jsonFile.page.rows.map(row => {
  row.columns.map(col =>{
    col.modules.map(mod => {
      switch(mod.type){
        case "text":
          // list of JSON handling functions;
          break;
        case "button":
          // list of JSON handling functions;
          break;
        case "image":
          // list of JSON handling functions;

        // etc...
      }
    })
  })
})

Since every content block is independent, I wanted to improve the speed of that loop and find a way to make the code asynchronous.

I'm quite new to asynchronous programming, and I've tried a few implementations of async/await without any luck (=> without any gain in terms of speed). This has lead me to a doubt: can async/await actually improve the performance of my code even if I don't have any call to external APIs in my code?

Can you suggest an approach to improve the speed of the above code? Thanks for your help!

Torakiki
  • 35
  • 6
  • What does the code inside the case statements do? Append to the dom? Modify some global variable? It seems you don't care about the return value of your `map` calls, in that case `forEach` is more appropriate than map. – Marius Mar 27 '19 at 11:11
  • 1
    The `async/await` is not about parallel processing that would bring you more performance. It's only about making calls that do not block. E.g. https://medium.com/front-end-weekly/async-await-is-not-about-making-asynchronous-code-synchronous-ba5937a0c11e – Wiktor Zychla Mar 27 '19 at 11:13
  • 1
    no, it doesn't do anything if you are not calling an external API. The whole point of async/await is that you can run other code while you are waiting for an I/O operation or response from an HTTP request. If you want to do things in parallel JavaScript is probably not a great choice. – Chris Rollins Mar 27 '19 at 11:15
  • HI @Marius, the code inside the statements performs some transformations on the JSON file (eg: creates a few extra properties). After that nested .map(), I use a few .pug files to create the HTML file. So you're right: I don't care particularly about a specific returned value. May I ask why you think that forEach should be more appropriate? Thanks! – Torakiki Mar 27 '19 at 13:58
  • @Torakiki This is discussed in this SO post: https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map – Marius Mar 27 '19 at 15:42

1 Answers1

0

Since JavaScript is single threaded .map does not provide any performance gains over a regular for loop. It is actually quite a bit slower than a regular for loop. See for instance this JSPerf.

Marius
  • 1,053
  • 2
  • 7
  • 16