JavaScript 引擎效能比較之二Google V8,javascript效能比較
Google V8 如日中天, 憑藉 Chrome 和 NodeJS 兩款應用, 在開發人員中有極好的口碑
先下載 v8 編譯產生若干所需的庫檔案
# 項目首頁
https://code.google.com/p/v8/
# 編譯安裝, 得先安裝 gjt,depot_tools , 參見以下連結, 在此略過
*https://code.google.com/p/v8-wiki/wiki/BuildingWithGYP
# 參考資料, 可能需翻牆
*https://developers.google.com/v8/embed
*https://developers.google.com/v8/get_started
*https://code.google.com/p/v8-wiki/wiki/BuildingWithGYP
# 測試程式 makefile.am如下, 測試環境為 macbook air, osx 10.10.3, Darwin Kernel Version 14.3.0 ,
V8Test_SOURCES = v8test.cpp
V8Test_CPPFLAGS = -I$(top_srcdir)/third_party/v8 -I$(top_srcdir)/util -pthread -lrt -stdlib=libstdc++ -std=c++11
V8Test_LDFLAGS = -L/workspace/cpp/v8/xcodebuild/Release -L$(top_srcdir)/util -stdlib=libstdc++ -std=c++11
V8Test_LDADD = -lv8_base -lv8_libbase -lv8_snapshot -lv8_libplatform -licuuc -licui18n -licudata
還是和上一篇一樣的 javascript arraysort.js:
function random_str(){ var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 8; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text;}var array = new Array();for ( var i = 0; i < 10000; i++) {array[array.length] = random_str();}debug_trace("begin sort and reverse array which length=" + array.length );array.sort();array.reverse();debug_trace("done, first element=" + array[0]+ ", " + "last element=" + array[array.length-1] );
現在由 V8 來執行, 看看測試結果如何
廢話不多說, 先上源碼 v8test.cpp, 根據 V8 內建的 shell.cc 改寫而來
#include "include/v8.h"#include "include/libplatform/libplatform.h"using namespace v8;long long current_timestamp(char arrTimeStr[TIME_FMT_LEN]) { struct timeval tv; struct tm* ptm; char time_string[40]; gettimeofday(&tv, NULL); // get current time if (arrTimeStr) { ptm = localtime(&tv.tv_sec); /* Format the date and time, down to a single second. */ strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm); /* Compute milliseconds from microseconds. */ //snprintf(char * restrict str, size_t size, const char * restrict format, snprintf(arrTimeStr, TIME_FMT_LEN, "%s.%06d", time_string, tv.tv_usec); } long long total_us = tv.tv_sec * 1000000LL + tv.tv_usec ; // caculate milliseconds // printf("milliseconds: %lld\n", milliseconds); return total_us;}// Extracts a C string from a V8 Utf8Value.const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>";}void debug_trace(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() > 0) { char szTimeStr[TIME_FMT_LEN] = { '\0' }; current_timestamp(szTimeStr); v8::String::Utf8Value str(args[0]); const char* cstr = ToCString(str); printf("[%s] %s\n", szTimeStr, cstr); }}v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = static_cast<int>(fread(&chars[i], 1, size - i, file)); i += read; } fclose(file); v8::Handle<v8::String> result = v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size); delete[] chars; return result;}v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate) { // Create a template for the global object. v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate); // Bind the global 'print' function to the C++ Print callback. global->Set(v8::String::NewFromUtf8(isolate, "debug_trace"), v8::FunctionTemplate::New(isolate, debug_trace)); return v8::Context::New(isolate, NULL, global);}void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) { v8::HandleScope handle_scope(isolate); v8::String::Utf8Value exception(try_catch->Exception()); const char* exception_string = ToCString(exception); v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { // V8 didn't provide any extra information about this error; just // print the exception. fprintf(stderr, "%s\n", exception_string); } else { // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { fprintf(stderr, "^"); } fprintf(stderr, "\n"); v8::String::Utf8Value stack_trace(try_catch->StackTrace()); if (stack_trace.length() > 0) { const char* stack_trace_string = ToCString(stack_trace); fprintf(stderr, "%s\n", stack_trace_string); } }}// Executes a string within the current v8 context.bool ExecuteString(v8::Isolate* isolate, v8::Handle<v8::String> source, v8::Handle<v8::Value> name, bool print_result, bool report_exceptions) { v8::HandleScope handle_scope(isolate); v8::TryCatch try_catch; v8::ScriptOrigin origin(name); v8::Handle<v8::Script> script = v8::Script::Compile(source, &origin); if (script.IsEmpty()) { // Print errors that happened during compilation. if (report_exceptions) ReportException(isolate, &try_catch); return false; } else { v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { assert(try_catch.HasCaught()); // Print errors that happened during execution. if (report_exceptions) ReportException(isolate, &try_catch); return false; } else { assert(!try_catch.HasCaught()); if (print_result && !result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. v8::String::Utf8Value str(result); const char* cstr = ToCString(str); printf("%s\n", cstr); } return true; } }}int main(int argc, char* argv[]) { // Initialize V8. V8::InitializeICU(); Platform* platform = platform::CreateDefaultPlatform(); V8::InitializePlatform(platform); V8::Initialize(); // Create a new Isolate and make it the current one. Isolate* isolate = Isolate::New(); { Isolate::Scope isolate_scope(isolate); // Create a stack-allocated handle scope. HandleScope handle_scope(isolate); // Create a new context. v8::Handle<v8::Context> context = CreateShellContext(isolate); if (context.IsEmpty()) { fprintf(stderr, "Error creating context\n"); return 1; } // Enter the context for compiling and running the hello world script. Context::Scope context_scope(context); // Create a string containing the JavaScript source code. Local<String> source;Local<String> filename; if (argc > 1) {filename = String::NewFromUtf8(isolate, argv[1]);source = ReadFile(isolate, argv[1]); } else { source = String::NewFromUtf8(isolate, "'Hello' + ', World!'");filename = String::NewFromUtf8(isolate, "nofile"); } long long begin_time = current_timestamp(NULL); ExecuteString(isolate, source,filename, false, true); long long end_time = current_timestamp(NULL); printf("calling costs %lld microseconds\n", end_time - begin_time); } // Dispose the isolate and tear down V8. isolate->Dispose(); V8::Dispose(); V8::ShutdownPlatform(); delete platform; return 0;}
對照測試結果如下
SpiderMonkey 執行此 JS 檔案共花費了 46.781 ms, 其中一萬個元素的字串數組排序反轉花費了 3 ms 不到的時間
$ ./test/SpiderMonkeyTest ./test/arraysort.js
[2015-05-10 08:22:20.246747] begin sort and reverse array which length=10000
[2015-05-10 08:22:20.249263] done, first element=zzvJWaQw, last element=00BpApzs
calling costs 46781 microseconds
V8 執行此 JS 檔案共花費了 22.326 ms, 其中一萬個元素的字串數組排序反轉花費了約 9 ms
$ ./test/V8Test ./test/arraysort.js
[2015-05-10 08:22:34.324314] begin sort and reverse array which length=10000
[2015-05-10 08:22:34.337588] done, first element=zzmBlrhz, last element=00G00Ssm
calling costs 22326 microseconds
總時間 V8 果然名不虛傳, 總的執行比 spidermonkey 快了一倍多, 但有趣的是在內部的字串數組排序反轉所花費的時間方面 SpiderMonkey 反而遙遙領先, 有待研究