作者:xillb_486 | 来源:互联网 | 2023-05-18 00:20
WhyGooglesV8JavaScriptengineinmyC++addonworkssignificantlyslowerthaninNode.JS?为什么谷歌在
Why Google's V8 Javascript engine in my C++ addon works significantly slower than in Node.JS?
为什么谷歌在我的c++ addon中使用的V8 Javascript引擎要比Node.JS中慢得多?
I've tried to write some stupidly simple code for generating prime numbers in the Javascript and ran it in V8 via my C++ addon and directly in Node.JS.
我尝试编写一些愚蠢的简单代码,用于在Javascript中生成质数,并在V8中通过我的c++ addon和Node.JS直接运行它。
I was quite shocked, because both should be using the same Javascript engine and both have executed the same code (time in milliseconds, less is better):
我非常震惊,因为两者都应该使用相同的Javascript引擎,并且都执行了相同的代码(时间单位为毫秒,越少越好):
V8 in Node.JS: 495517
V8 in Node.JS C++ Addon: 623598
Here is the source of Javascript module and source of C++ addon that runs same Javascript code (and I think problem not in the interop, because measuring of time works directly in JS):
这是Javascript模块的源代码和c++ addon的源代码,它运行相同的Javascript代码(我认为在内部操作中没有问题,因为时间度量直接在JS中工作):
index.js:
index.js:
var jsInNodeJsPrimeGeneratorBenchmark = require("./Javascript.js");
var jsInNativePrimeGeneratorBenchmark = require("./native");
console.log("V8 in Node.JS: ", jsInNodeJsPrimeGeneratorBenchmark.primeGeneratorBenchmark());
console.log("V8 in Node.JS C++ Addon: ", jsInNativePrimeGeneratorBenchmark.primeGeneratorBenchmark());
Javascript.js:
Javascript.js:
function primeGeneratorBenchmark() {
var result, primeNumberCounter, i, j, isPrime, start, end;
i = 3;
primeNumberCounter = 1;
start = Date.now();
while (primeNumberCounter <100000) {
isPrime = true;
for (j = 2; j
native.cpp:
native.cpp:
#include
v8::Handle primeGeneratorBenchmark(const v8::Arguments &arguments);
void registerModule(v8::Handle target);
v8::Handle primeGeneratorBenchmark(const v8::Arguments &arguments) {
v8::HandleScope handleScope;
v8::Local cOntext= arguments.Holder()->CreationContext();
v8::Context::Scope scope(context);
const char *sourceStringC =
"var result, primeNumberCounter, i, j, isPrime, start, end, time;\n"
"i = 3;\n"
"primeNumberCounter = 1;\n"
"start = Date.now();\n"
"while (primeNumberCounter <100000) {\n"
" isPrime = true;\n"
" for (j = 2; j sourceStringV8 = v8::String::New(sourceStringC);
v8::Local script = v8::Script::Compile(sourceStringV8);
script->Run();
v8::Local timeResult = v8::Context::GetCurrent()->Global()->Get(v8::String::New("time"));
return handleScope.Close(timeResult);
}
void registerModule(v8::Handle target) {
target->Set(v8::String::NewSymbol("primeGeneratorBenchmark"), v8::FunctionTemplate::New(primeGeneratorBenchmark)->GetFunction());
}
NODE_MODULE(native, registerModule);
1 个解决方案