N
N
Nadim Zakirov2020-04-30 10:33:18
JavaScript
Nadim Zakirov, 2020-04-30 10:33:18

How to speed up JavaScript execution in the browser? How to parallelize JavaScript?

How could you parallelize JavaScript execution in a browser? For example, if you generate a lot of frames and carry out calculations inside them in parts, will they be executed in separate threads in parallel?

Explanations if details are needed
Дело в том, что у меня возникала нестандартная задача по парсингу больших объемов текста посредством регулярных выражений (конкретно в браузере). Нестандартность заключается в том, что разобрать тексты нужно максимально быстро: каждую секунду я получаю 10 текстов, на разбор каждого текста регулярками уходит в среднем 3 секунды, если обрабатывать тексты последовательно, это уйдет целых пол минуты, прежде, чем я получу результат по всем 10-ти текстам. Соответственно, у меня закономерно возникает вопрос, а не могу ли я каким-нибудь хитрым трюком распаралелить код? Например, каждый полученный текст разбирать в своем фрейме или popup-окне? Как обычно в таких случаях поступают, когда надо выполнить код в браузере в несколько потоков?

Thanks in advance to everyone who is ready to help with advice or a guiding kick. I will add that I have no restrictions in terms of resources, the code will be executed in the browser on a physical server with a bunch of cores and a lot of RAM.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Belyaev, 2020-04-30
@bingo347

Definitely need to take out this work in WebWorkers
Here you can read: https://developer.mozilla.org/en/docs/DOM/Using_we...
Well, in terms of acceleration, is it really necessary to parse the text with regular expressions? Regulators are very slow. And on large volumes of text, it naturally becomes noticeable. Parsing text with a narrowly focused algorithm made for a specific data format will be many times faster if done correctly.

N
ned4ded, 2020-04-30
@ned4ded

Parallelize - no, but you can chunk text and parse chunks of it asynchronously, which will free up the main thread.

const arr = [1, 2, 3, 4, 5];

const rec = (theArr) => {
    const [first, ...rest] = theArr;

    if (!first) return;

    setTimeout(() => {
        /* do some parsing, example: */
        if ([3, 4].includes(first)) alert('found it!');

        return rec(rest);
    }, 0);
};

rec(arr);

H
hzzzzl, 2020-04-30
@hzzzzl

there are web workers that run in a separate process, but I didn’t deal with them, except “just try to play around”, so I won’t tell you here
https://developer.mozilla.org/ru/docs/Web/API/Web_ ...
and if you wrap it in promises, it won't get faster?

function parse(txt = '') {
  return Promise.resolve(txt.match(/a/gi))
}

texts = ['astajf;lj3', 'AAjfjia33r', '4jlj;lajaaa', 'afdj df jas fjsa ja33a']

await Promise.all(texts.map(parse))
// (4) [Array(2), Array(3), Array(4), Array(5)]

X
xmoonlight, 2020-04-30
@xmoonlight

The simplest option:
includeHTML, create one js nickname with a processing function, and load it several times in a cycle: as soon as the load request leaves, the next cycle immediately starts without waiting! .
Immediately after loading, in the handler, call the function with the necessary parameters and it immediately starts counting/parsing/etc.
And so, for all iterations of the loop: everything happens in parallel!
If necessary, keep track and control the number of active/simultaneously executing scripts through the counter variable.
Everything works asynchronously!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question