Using threading, you can make a new thread and tell the thread to run a function, from the parent thread. This library is loosely inspired by Pythons threading
module. So, it has a similar API, yet javascript-ified
Using worker_threads
from NodeJS, you can use threads, but it isn't a nice experience, as you have to essentially make your own communication protocol for your application and the threads you make. However, simple-threading
makes it easier. Here's a simple example:
import Thread from "simple-threading";
function veryExpensiveCalculation(){
for(let i=0;i<10_000_000, i++){};
return "finished";
}
new Thread(veryExpensiveCalculation)
.start()
.then(({result, end})=>{
result // "finished"
end() // End the thread. If not called, it will be terminated anyway, after this. However, if you need to use the thread after this,
});
Note that if you really need high performance for performance-intensive applications, I would firstly recommend something other than Javascript. Perhaps Rust, I hear that's pretty fast.
However, if you do plan to stick with Javascript, then maybe this package isn't for you. While it does have a low footprint, it still is slightly less efficient than writing the code yourself. Not by much though. Really the only overhead that simple-threading
adds over regular code is its use of new Function
in the thread file itself. This is easily the most expensive call made by it, however, it isn't much of penalty, but of course, if you wrote the code for your project in particular, it would mean that (potentially) no new Function
calls are needed.