Cover by Brian Carper, Christophe Grand, Chas Emerick

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Optimizing Numeric Performance

Clojure provides all the raw materials needed to model and implement data- and mathematics-intensive algorithms clearly and concisely. However, while expressivity is important, performance is often an overriding concern in such cases—it’s what drives programmers everywhere who would otherwise prefer higher-level languages to implement performance-critical sections of their programs in languages like C and Fortran. That’s a fine coping mechanism, and can always be a measure of last resort,[340] but is often a source of integration, build, and deployment complexity (not to mention a sap on developer productivity). Thus, the more we can do in our high-level language, the happier and more productive we’ll be.

So, how can we maximize the performance of numerics-intensive code in Clojure?

Use primitives. As we discussed in Clojure Has a Mixed Numerics Model, primitives are not burdened by the allocation and garbage-collection costs associated with boxed numbers, and most operations over them are implemented at very low levels (often the hardware itself). All other things being equal, the same algorithm[341] implemented to utilize primitives will often be an order of magnitude faster than if boxed numbers are used. Doing this within Clojure will allow you to implement algorithms that approach the runtime performance of the same functionality implemented in Java.

Avoid collections and seqs. A corollary to the notion of using primitives whenever possible where ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required