In my application i am generating JavaScript code which is following CPS style. I am 'not' using any 'continuations' as such. No async behavior, No pause and resume, and No callbacks.
Just that the code is following a continuation passing style of programming.
There are many stages to the functionality, each stage does its processing and passes the result to its continuation.
What i find is that performance of CPS styled code is very poor. Code written in direct style is almost 150 times faster than the CPS styled code.
Please check the below code.
Both below codes are equivalent to
var res = data.store.bookshelf.book.author;
Direct Styled Code :
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);
The above code runs in almost 95 ms.
CPS Styled Code:
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);
The above CPS styled code runs in 15000 ms
Is there anything i can do to improve the CPS styled code? OR JavaScript is inherently not suitable for CPS styled code?
The above tests are done on node.js version 0.6.12
Can someone please throw some light on this issue?
Thanks,