乐趣区

关于c++:Need-For-Speed-Nodejs-Module-In-C

Introduction

The reason can’t be more simple: the need for speed.

According to a simple test between node-uuid and C++ uuid, the truth was told: C++ is faster.

The time consumptions of 1M generations of uuid is almost 3s(node-uuid) vs. 0.3s(C++ modules based on boost uuid).

So, the advices is: crucial module should be written in C++, if you have time for this.

node-uuid Module in C++

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

test.js

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

console.log('uuid:', uuid.next());
console.log('uuid.count +' uuid(s) has/have been generated.');

Good luck!

退出移动版