您的位置:首页 > Web前端 > Node.js

Why Should Write Node Modules In C++ If Possible.

2014-09-22 04:34 363 查看
The reason can't be more simple: the Need For Speed.

As a simple test between node-uuid and my own uuid implementations by boost, the result exposures the truth again: C++ is still faster than Javascript.

The time consumptions of 1M generations of uuid is almost 3s(node-uuid) to 0.3s(my boost uuid).

So, my advices is: if possible, write Node module by yourself with C++, the benefit is undeniable.

The following is the code of boost uuid:

node-uuid.h

#ifndef NODE_UUID_H
#define NODE_UUID_H

using namespace v8;

#define NODE_UUID_CLS_NAME "nodeUuid"

namespace igame
{
  namespace uuid {
    void initialize(Handle<Object> exports);
  }
} // ns

#endif
node-uuid.cpp

#include "node_uuid.hpp"

// #include <boost/lexical_cast.hpp>

namespace igame
{
  namespace uuid {
    Persistent<Function> constructor;
    buid::random_generator uuid_generator;
    uint32_t uuid_count;

    Handle<Value> generate_uuid(const Arguments& args);
    Handle<Value> get_count(Local<String> property, const AccessorInfo& info);

    void initialize(Handle<Object> exports)
    {
      exports->Set(String::NewSymbol("next"), FunctionTemplate::New(generate_uuid)->GetFunction());
      exports->SetAccessor(String::NewSymbol("count"), get_count, NULL);
    }

    Handle<Value> generate_uuid(const Arguments& args)
    {
      HandleScope scope;

      buid::uuid uid = uuid_generator();
      uuid_count++;

      return scope.Close(String::New(buid::to_string(uid).c_str()));
    }

    Handle<Value> get_count(Local<String> property, const AccessorInfo& info)
    {
      HandleScope scope;

      return scope.Close(Integer::New(uuid_count));
    }
  } // ns
} // ns


test.js

var uuid = require('./build/Release/node-uuid');

console.log('uuid:', uuid.next());
console.log('uuid.count + ' uuid(s) has/have been generated.');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: