Javascript Webworkers

Asked

Viewed 29 times

0

I’m studying a little webworkers and created that 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>

Code of the webworker:

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:

  • Webworker-free: start: 5378ms
  • With webworker: start: 18969ms

The difference is very big. Because the worker works on another thread, I imagined that 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 button "Say HI" that it will work, but the fact of calling it 1 or N times interferes in the final time that the webworker will take to finish the task.

Is that right? It should take so much longer to process something?

  • 1

    Related, perhaps duplicate, https://answall.com/questions/1946

  • Excellent response

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.