I'm studying a bit of webworkers
and I created this scenario:
<html>
<head>
<meta charset="utf-8" />
</head>
<script src="index.js"></script>
<script src="Http.js"></script>
<body>
<div id="log">
<button onclick="sayHI()">Say HI</button>
<output id="result"></output>
</div>
<script>
function sayHI() {
console.log('oi');
}
let options = {
length: 1000000
}
let vetor = [];
console.time('start');
for (let i = 0; i < options.length; i++) {
let obj = {
id: Math.random() * 10,
timestamp: new Date(),
nome: (Math.random()).toString().split(0, 50)[0],
sobrenome: (Math.random()).toString().split(0, 100)[0],
seila: (Math.random()).toString().split(0, 500)[0],
}
vetor.push(obj);
}
console.timeEnd('start');
/*
let worker = new Worker('index.js');
worker.addEventListener('message', function (e) {
vetor.push(e.data.obj);
if ((e.data.length +1 )== options.length) {
console.timeEnd('start');
}
}, false);
worker.postMessage(options);*/
</script>
</body>
</html>
Webworker code:
addEventListener('message', function (e) {
for (let i = 0; i < e.data.length; i++) {
let obj = {
id: Math.random() * 10,
timestamp: new Date(),
nome: (Math.random()).toString().split(0, 50)[0],
sobrenome: (Math.random()).toString().split(0, 100)[0],
seila: (Math.random()).toString().split(0, 500)[0],
}
postMessage({obj: obj, length: i});
}
});
Running the two examples I got these results:
-
No webworker: start:
5378ms
-
With webworker: start:
18969ms
The difference is very large. Because the worker worked on another thread, I figured the performance would be similar or even better. But what I realized is that, because it is a new thread, I can quietly keep calling my "HI" button that will work, but calling it 1 or N sometimes interferes with the final time the webworker goes take it to finish the task.
Is that right? Should it take such a long time to process anything?