Skip to content

Instantly share code, notes, and snippets.

@AoJ
Last active February 8, 2019 00:16
Show Gist options
  • Save AoJ/547bc678347c18a4051c to your computer and use it in GitHub Desktop.
Save AoJ/547bc678347c18a4051c to your computer and use it in GitHub Desktop.
Js vs C++ vs Rust in node.js

Test node.js peformance for fibonacci implemented with js, cpp and rust

  fibonacci(10)
  js   x 1,308,359 ops/sec ±1.84% (96 runs sampled)
  cpp  x 4,146,280 ops/sec ±1.70% (93 runs sampled)
  rust x 3,675,842 ops/sec ±1.21% (97 runs sampled)
  
  fibonacci(33)
  js   x  20.87 ops/sec ±2.32% (39 runs sampled)
  cpp  x  77.82 ops/sec ±1.47% (69 runs sampled)
  rust x 150 ops/sec ±1.19% (87 runs sampled)
#include <node.h>
using namespace v8;
inline int fibonacci(int n) {
if (n < 2) { return 1; }
return fibonacci(n - 1) + fibonacci(n - 2);
}
void Fibonacci(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
if (!args[0]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
int value = args[0]->NumberValue();
args.GetReturnValue().Set(Number::New(isolate, fibonacci(value)));
}
void init(Local<Object> exports, Local<Object> module) {
NODE_SET_METHOD(module, "exports", Fibonacci);
}
NODE_MODULE(addon, init)
function fibonacci(n) {
if (n < 2) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
module.exports = function (n) {
if(typeof n != "number") throw new Error('Wrong arguments');
return fibonacci(n);
}
#[macro_use]
extern crate neon;
use neon::vm::{Call, JsResult, Module};
use neon::js::JsInteger;
use neon::mem::Handle;
#[inline(always)]
fn fibonacci(n: i32) -> i32 {
return match n {
1 | 2 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2)
}
}
fn fib(call: Call) -> JsResult<JsInteger> {
let scope = call.scope;
let count: Handle<JsInteger> = try!(try!(call.arguments.require(scope, 0)).check::<JsInteger>());
Ok(JsInteger::new(scope, fibonacci(count.value() as i32)))
}
register_module!(m, {
m.export("fibonacci", fib)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment