C++写node笔记(四)
by snoopyxdy
at 2012-11-30 09:42:00
original http://snoopyxdy.blog.163.com/blog/static/601174402012103092114682
一个简单的模块目录构成,不知道写的对不对,反正我就这么弄了,哈哈。verify
/index.js
/package.json
/readme.md
/lib
/verify.js
/addon
/binding.gyp
/SimpleVerify.cc
/SimpleVerify.h
/verify.cc
#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "SimpleVerify.h"
using namespace v8;
void Init(Handle<Object> target) {
target->Set(String::NewSymbol("isArray"),
FunctionTemplate::New(SimpleV::isArray)->GetFunction());
target->Set(String::NewSymbol("isNumber"),
FunctionTemplate::New(SimpleV::isNumber)->GetFunction());
}
NODE_MODULE(verify, Init)
#ifndef SV_H
#define SV_H
#include <node.h>
class SimpleV {
public:
static v8::Handle<v8::Value> isArray(const v8::Arguments& args);
static v8::Handle<v8::Value> isNumber(const v8::Arguments& args);
private:
SimpleV();
~SimpleV();
};
#endif
#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "SimpleVerify.h"
using namespace v8;
SimpleV::SimpleV() {};
SimpleV::~SimpleV() {};
Handle<Value> SimpleV::isArray(const Arguments& args) {//定义是否是数组
HandleScope scope;
return scope.Close(Boolean::New(args[0]->IsArray()));
}
Handle<Value> SimpleV::isNumber(const Arguments& args) {//定义是否是数字
HandleScope scope;
return scope.Close(Boolean::New(args[0]->IsNumber()));
}
测试环境:linux虚拟机,不多介绍了,具体测试结果可能跟机器配置有关系var sv = module.exports = require('./lib/verify.js');
//利用纯js语法进行判断
var ia = Array.isArray;
console.time('js');
for(var j=0;j<1000;j++){
ia([]);
ia('111');
isNaN(123);
isNaN('abc');
}
console.timeEnd('js')
//利用c++模块进行判断
var ia2 = sv.isArray;
var in2 = sv.isNumber;
console.time('c++');
for(var j=0;j<1000;j++){
ia2([]);
ia2('111');
in2(123);
in2('abc');
}
console.timeEnd('c++');
我们可以看到尽管我们利用了js原生的isNaN和isArray这2个方法,但是从性能上来说,无疑C++验证的更快一些。js: 10ms
c++: 3ms
js: 9ms
c++: 1ms
js: 7ms
c++: 2ms
js: 8ms
c++: 0ms
js: 6ms
c++: 0ms