The example says it all:
user> (time (dotimes [i 10000000] (inc i)))
"Elapsed time: 413.948711 msecs"
nil
user> (time (let [new-inc inc] (dotimes [i 10000000] (new-inc i))))
"Elapsed time: 1034.722729 msecs"
nil
I believe the compiler inlines certain core functions like inc
, especially when applied to primitive arguments.
When you use inc
as a regular function (e.g. passing to higher order functions, aliasing with let
etc.), performance may therefore be worse because it loses the ability to inline. The extra overhead comes from making an extra function call, any maybe also the cost of boxing one or more arguments.
This isn't a limitation of Clojure, just reflects the fact that the compiler isn't yet very sophisticated with its optimisations. You can probably expect things like this to get much better in future versions of Clojure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With