Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come functions in core run faster when not bound locally?

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
like image 896
ToBeReplaced Avatar asked Jun 05 '13 22:06

ToBeReplaced


1 Answers

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.

like image 138
mikera Avatar answered Oct 21 '22 06:10

mikera