Quack!

If it talks like a duck and walks like a duck, then it must be a duck… and, apparently, it’ll waddle a good deal faster than a turkey, or any other non-duck species.

I’ve been meaning to get to the subject of duck typing and performance ever since I saw Sean give his presentation at CFUnited. Unfortunately, the performance aspect of going duck was what caught most people’s attention; as Sean shouts out duck typing is not about performance.

I finally got round to downloading Sean’s source code and ran some tests of my own. Here’s the low-down - performance is affected only when the argument type or return type is specified as a CFC; if it is anything else, performance is about equal to the duck typed equivalents. If you’re typing arguments and return values to structs, arrays, strings, numbers, whatever, duck typing will not give you any performance gains. Apologies all if I’m repeating what’s already been pointed out; I searched around a bit and couldn’t find anyone else commenting on this particular detail.

CFC type checking is always going to be more expensive than checking any other type, since we need to jump through many of the same hoops as we do during createObject() to actually resolve the path to the CFC template - is the path to type being checked relative or absolute? Is it referenced via a mapping? Is the type being checked a supertype of the type passed in? You get the idea; evaluating these kinds of complex relationships is expensive.

So do duck type if your design calls for it, or if you’re having serious performance problems with code that checks for CFC types. Otherwise, make like a monkey and code!

Update: You can download the code I used for testing here. It’s identical to Sean’s code, with the exception of a new typedNative function in performance.cfm, which is used to test for “native” types, i.e., Struct, Array, whatever.