Possible Duplicate:
Performance difference between functions and pattern matching in Mathematica
I often find a heavy use of pure functions in a lot of the answers posted here, and often those solutions are much faster than using named patterns etc. Why is this so? Why are pure functions faster than others? Does it have to do with the mma interpreter having to do less work?
First, let us consider some sample benchmarks:
Pure functions are often (much) faster for 2 reasons. First, anonymous pure functions (those defined with the slots –
#and&) do not need to resolve name conflicts for variable names. Therefore, they are somewhat faster than pattern-defined ones, where some name conflict resolution takes place. But you see that pure functions with named variables are actually slower, not faster, than pattern-defined ones. I can speculate that this is because they also have to resolve possible conflicts inside their body, while rule-based ones ignore such conflicts. In nay case, speed differences are of the order of 10-20 %.Another, and much more dramatic, difference is when they are used in functions such as Map, Scan, Table, etc, because the latter auto-compile on large numerical (packed) lists. But while pure functions can often be compiled, pattern-defined ones fundamentally can not, so this speed gain is inaccessible to them. For example: