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

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.');






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章