A difference between cfloop and for loop in cfscript

I am moving key parts of a codebase to cfscript to take advantage of the speed boost that comes with using cfscript. Along the way I’m discovering the differences between tag-based Coldfusion and cfscript.

Today this was the bug I worked out:

This code will delete 10 widgets:




 

This cfscript will only delete 5 widgets:

var i = 1;
setNumberofWidgets(10);
for(i=1;i<=getWidgetTotal();i++)
{
deleteAWidget();
}

This is because getWidgetTotal() will be called on each iteration of the loop. After deleting 5 widgets the loop will exit because there will only be 5 widgets left and i will equal 5. The cfloop tag from the first example will only evaluate once before starting the loop.

This cfscript will delete 10 widgets:

var i = 1;
var total = getWidgetTotal();
setNumberofWidgets(10);
for(i=1;i<=total;i++)
{
deleteAWidget();
}

By calling the function before starting the loop we can get the total number of widgets and are then able to complete the loop.

3 thoughts on “A difference between cfloop and for loop in cfscript”

  1. Hey Dan, long time no speak. Hope things are good.

    On this topic, I don’t believe there is a speed boost any longer for CFScript. If I recall correctly, this was once true (say CF6) but hasn’t been true for a couple versions at least.

    That being said, I am a fan of the scripting syntax but cfscript, while much improved since CF9, still isn’t 100%.

    1. Hey Brian! Thanks for stopping by.

      Recent articles on cfscript performance on the web agree with you that there’s a negligible difference, however after looking for ways to speed up some long running processes I decided to give it a try and was happy to find it was much faster in my testing.

      We have a base object here that all other cfcs extend from. By rewriting the base cfc in cfscript I was able to improve the speed of one of the heavier function calls by 64% (1306ms vs 464ms). That’s a speed up end users can notice. In my testing it sped things up by 40% on average. We’re now in the process of looking for other low hanging fruit to convert to cfscript to see what (if any) speed we can gain.

      Of the functions I tested 64% was the biggest speed up, with 47-49% being the middle values and 8% speed up being the smallest gain in speed. Ironically it was the function with the lowest gain that I was working hardest to try an optimize which lead me to attempting the rewrite.

      I’ve just released my cftag2cfscript script onto github so that those that would like to move their legacy code into cfscript (or maybe those that want to test for performance themselves) can give it a shot.

Leave a Reply

Your email address will not be published. Required fields are marked *