神刀安全网

Clojurescript’s areduce is faster than native javascript reduce

Power of expression vs. Performances

map and reduce are the basic building blocks of functional programming.

The essence of map and reduce is that they give you – the developer – more power of expression over the equivalent piece of code using a while or a for loop.

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 reduce in javascript . But, fortunately, 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.

javascript: reduce vs. for loop

Let’s compare the performaces of reduce and for for sum-of-squares , withKLIPSE.

We are using js* to embedd javascript code into clojurescript .

In javascript , reduce is around 5 times slower than for .

Feel free to modify js-arr and press Ctrl-Enter a couple of times to benchmark like you wish.

Clojurescript areduce

In clojure and clojurescript there is a handy way to reduce over native arrays.

Please welcome areduce .

With 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 ret .

Obviously, 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 javascript code:

Observe the transpiled javascript code: It’s very close to the implementation, you’d have written for sum-of-squares , before reduce was available in javascript . (Maybe you’d chosen better names for the variables.)

From the power of expression perspective, areduce is as powerful are reduce .

We will investigate the performance of areduce in the next paragraph.

Clojurescript areduce vs. Javascript reduce

Now, it’s obvious why areduce is faster that javascript ’s reduce : 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.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Clojurescript’s areduce is faster than native javascript reduce

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮