DEV Community

Mozzammel Haque
Mozzammel Haque

Posted on

Calling Rust from Node with napi-rs: 6x faster for heavy work, 19x slower for tiny calls

I called a Rust function from Node 5 million times. It was 19x slower than the same function in plain JavaScript.

The function just adds two numbers. About 106 ns per native call against 5.5 ns in JS, because V8 inlines the JS version and the native one has to cross the boundary every time.
Then I gave Rust real work. Recursive fib(38) went from 726 ms to 116 ms, about 6x faster. A prime sieve over 20M numbers was only 1.5x faster.

The part that surprised me most: passing a plain JS array of 1M numbers into Rust took 85 ms. A Float64Array took 1.3 ms, same as a JS loop.

On my 2 vCPU box, native code started to pay off once the JS version of a call took around a microsecond. I did not test WASM because I couldn't install the target in my sandbox.

Full numbers, code and raw output are in the article:

https://medium.com/gitconnected/calling-rust-from-node-with-napi-rs-6x-faster-for-heavy-work-19x-slower-for-tiny-calls-fe0f8828924b?sharedUserId=mozzammeluiu

Top comments (0)