By Peter Bell

Duck Typing for Performance

Firstly, please note Duck typing (see Sean Corfields excellent presentation) is NOT primarily about performance. In most cases this is probably the least interesting aspect of it. Using duck typing to improve performance before identifying a performance bottleneck is a sure sign of Premature Optimization :->

Once you have a working application with a performance bottleneck which can be attributed to a large number of method calls each of which does a relatively small amount of processing, it is time to consider taking advantage of duck typing to improve the performance . . .

According to Sean (and based on both his and Joe Rinehart’s experience in duck typing the core of Fusebox 5 and Model Glue respectively), removing the returntype from methods, and the type and the required="true" from cfarguments can increase application performance.

The way he describes it, at runtime, if ColdFusion sees a type, it has to run some code to validate that type. Doing so slows down the application. How much that matters depends on the number of method calls and the amount of processing each is doing. In his presentation at CF United, Sean showed an extreme example of calling a method that did nothing but return the passed value back. The un-typed version was 30-40 times faster than the typed version. He and Joe both reported a 2-3 times performance increase on the core of the frameworks they did this for. Your mileage will obviously vary.

What is the downside? Not a lot! The main downside is that if you have code that passes an invalid value type in, the error will not be caught at runtime until your application tries to do something with the invalidly typed value rather than on the invalid typed value being passed in.

Most of the time this just means that instead of getting a runtime type error you'll get a different error (which may or may not be a little harder to debug). The risk is that if you have test cases that don't fully exercise your code you might have code that passes your tests which would otherwise have failed, leaving a bug in the code which may be harder to find. But that is OK, because we all use CFC Unit (written by Paul Kenney) and a Test Driven Development approach to exercise our classes exhaustively :->

A bigger problem is the lack of documentation. I like to leave typing in as it more clearly documents the intent of my method interfaces (it is also required for remote interfaces). If you want to keep the documentation benefits but need the performance boost, there is a solution.

Anyone looking for more information on Duck typing should check out Judith's great article over at Fusion Authority.

Comments
BlogCFC was created by Raymond Camden. This blog is running version 5.005.