在我的應用程序中,我生成的JavaScript代碼遵循CPS風格。我'不'使用任何'延續'。沒有異步行爲,沒有暫停和恢復,沒有回調。JavaScript:直接代碼與CPS風格的生成代碼性能比較
只是代碼是在編程的continuation passing style之後。
功能有很多階段,每個階段都會處理並將結果傳遞給它的延續。
我發現的是CPS樣式代碼的性能非常差。以直接樣式編寫的代碼比CPS樣式代碼快150倍。
請檢查以下代碼。
下面兩個碼是等同於
var res = data.store.bookshelf.book.author;
直接樣式化代碼:
var data = { store : { bookshelf : {book : {author:"Douglas Crockford"}}}};
var t1 = new Date().getTime();
for(var i = 0; i < 1000*1000*100; i+=1){
var temp0 = data;
var temp1 = temp0.store;
var temp2 = temp1.bookshelf;
var temp3 = temp2.book;
var temp4 = temp3.author;
var res = temp4;
}
var t2 = new Date().getTime();
console.log(t2-t1);
上面的代碼運行在近95毫秒。
CPS樂府代碼:
var data = { store : { bookshelf : {book : {author:"Douglas Crockford"}}}};
// return the variable to the continuation
function cps_VARREF(x,f){
return f(x);
}
// get the value of the property from the variable and pass it to the continuation
function cps_CHILD(x,child,f){
return f(x[child]);
}
// simply return the input value, essentially closing the continuation chain
function ret_(x){
return x;
}
var t1 = new Date().getTime();
for(var i = 0; i < 1000*1000*100; i+=1){
var res = function(c_){
return cps_VARREF(data,function(x1){
return cps_CHILD(x1,"store",function(x2){
return cps_CHILD(x2,"bookshelf",function(x3){
return cps_CHILD(x3,"book",function(x4){
return cps_CHILD(x4,"author",c_);});});});});}(ret_);
}
var t2 = new Date().getTime();
console.log(t2-t1);
以上CPS風格的代碼在15000毫秒
運行有什麼我可以做,以提高代碼風格的CPS?或者JavaScript本質上不適用於CPS風格的代碼?
上述試驗是在node.js的版本0.6.12
做某人能請扔在這個問題上有些輕?
感謝,
瀏覽器測試一個http://jsperf.com/copast-vs-direct只顯示1:10運行時間比例 – Bergi