Web Worker 20x worse performance

I can't seem to find a definite answer.

I have a very simple POC that computes the same function synchronously and asynchronously.

worker.js

onmessage = function(e) { var s = new Date().getTime(); i = 0; var avg = Math.random(); while ( i < e.data ){ avg = (avg + Math.random()) / 2 ; i++; } var d = new Date().getTime(); console.log( 'Duration ' + (d - s) ); postMessage( avg ); } 

Index.html

 <script> var mw = new Worker("worker.js"); mw.onmessage = function(e) { console.log('Worker says: ' + e.data); }; function av ( j ){ var s = new Date().getTime(); i = 0; var avg = Math.random(); while ( i < j ){ avg = (avg + Math.random()) / 2 ; i++; } var d = new Date().getTime(); console.log( 'Result is ' + avg ); console.log( 'Duration ' + (d - s) ); } function runSync(){ av( 100000000 ); } function runAsync(){ mw.postMessage( 100000000 ); } </script> <a href="#" onClick="runSync()" /> Run Sync </a> <a href="#" onClick="runAsync()" /> Run Async </a> 

On my 4-core MacBook, this generates:

 Result is 0.47398200501358567 Duration 985 Duration 23187 Worker says: 0.7422913957976759 

As you can see, the web worker takes 20 times longer. What is the explanation for this? Other related posts suggested garbage collection and heap, but then found that the culprit was some kind of API problem. I really want to understand what workers are and not. Do they have some odd performance rating when running the garbage collector? If so, how do you manage your memory in such a way as to avoid such bottlenecks?

+6
source share
1 answer

They are not exactly the same function, you are executing e.data on a worker, which is much slower than accessing cached j directly, if you change this, they should take about the same time.

0
source

All Articles