Power of expression vs. Performances
reduce are the basic building blocks of functional programming.
The essence of
reduce is that they give you – the developer – more power of expression over the equivalent piece of code using a
while or a
And the power of expression is an important part of SW development.
But very often, there is a trade-off between power of expression and performances. It’s the case with
Clojurescript comes to the rescue with its super-powerful macros and we – the clojurescript developers – enjoy both high performances an the power of expression.
In this article, we show illustrate this idea dealing with a function that calculates the sum of the squares of an array of numbers.
Let’s compare the performaces of
sum-of-squares , withKLIPSE.
We are using
js* to embedd
reduce is around 5 times slower than
Feel free to modify
js-arr and press
Ctrl-Enter a couple of times to benchmark like you wish.
In clojure and clojurescript there is a handy way to reduce over native arrays.
Please welcome areduce .
areduce you pass an expression instead of a function
(areduce a idx ret init expr)
areduce reduces an expression across an array
a , using an index named
idx , and return value named
ret , initialized to
init , setting
ret to the evaluation of
expr at each step, returning
areduce is a macro.
It sounds complex, but with an example it will be very clear. Let’s implement our sum of squares using
areduce and have a look at the transpiled
Observe the transpiled
sum-of-squares , before
reduce was available in
From the power of expression perspective,
areduce is as powerful are
We will investigate the performance of
areduce in the next paragraph.
Now, it’s obvious why
areduce is faster that
areduce is a macro that allows you – the developer – to write elegant code that is translated at compile time to fast native code.
Let’s see it in action withKLIPSE.