在我的应用程序中,我正在生成遵循 CPS 样式的 JavaScript 代码。我“不”使用任何“延续”。没有异步行为,没有暂停和恢复,没有回调。
只是代码遵循了一种延续传递的编程风格。
功能有许多阶段,每个阶段都进行处理并将结果传递给其延续。
我发现 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版本上完成的
有人可以对这个问题有所了解吗?
谢谢,