如何提升Node执行效率

Node.js基予Google V8引擎,性能优秀,但JavaScript毕竟是脚本语言,和C/C++相比还是有差距的,本文通过计算fibnacci数列来对比Node Addon和JavaScript之间的性能差距,对性能有要求可以作为参考。

 1 // addon.cc
 2 #include <node.h>
 3 
 4 namespace demo {
 5 
 6 using v8::Exception;
 7 using v8::FunctionCallbackInfo;
 8 using v8::Isolate;
 9 using v8::Local;
10 using v8::Number;
11 using v8::Object;
12 using v8::String;
13 using v8::Value;
14 
15 int fib(int v)
16 {
17     if (v == 0) return 0;
18     else if (v == 1) return 1;
19     else return fib(v - 1) + fib(v - 2);
20 }
21 
22 void Calc(const FunctionCallbackInfo<Value>& args) {
23   Isolate* isolate = args.GetIsolate();
24 
25   if (args.Length() < 1) {
26     // Throw an Error that is passed back to JavaScript
27     isolate->ThrowException(Exception::TypeError(
28         String::NewFromUtf8(isolate, "Wrong number of arguments")));
29     return;
30   }
31 
32   // Check the argument types
33   if (!args[0]->IsNumber()) {
34     isolate->ThrowException(Exception::TypeError(
35         String::NewFromUtf8(isolate, "Wrong arguments")));
36     return;
37   }
38 
39   // Perform the operation
40   int value = (int)args[0]->NumberValue();
41   
42   int f = fib(value);
43   
44   Local<Number> num = Number::New(isolate, f);
45 
46   args.GetReturnValue().Set(num);
47 }
48 
49 void Init(Local<Object> exports) {
50   NODE_SET_METHOD(exports, "fib", Calc);
51 }
52 
53 NODE_MODULE(addon, Init)
54 
55 }  // namespace demo

 

 1 // hello.js
 2 const addon = require('./build/Release/addon');
 3 
 4 // C++ 计算
 5 console.log(new Date().toLocaleString());
 6 console.log('The C++ result is: ', addon.fib(45));
 7 console.log(new Date().toLocaleString());
 8 
 9 
10 // JavaScript 计算
11 function fib(v) {
12     if (v == 0) return 0;
13     else if (v == 1) return 1;
14     else return fib(v - 1) + fib(v - 2);
15 }
16 
17 console.log('The js result is: ', fib(45));
18 console.log(new Date().toLocaleString());

结果很明显-------------------------------

 参考代码:https://git.oschina.net/zhujf21st/node-performance.git

posted @ 2016-08-17 13:38  jeffrey.chu  阅读(363)  评论(0编辑  收藏  举报

99code棋牌网