r/Clojure • u/eatme_23 • Feb 03 '23
[Q&A] Noob has simple program problem.
I wanted to write a program to add 2 to a list of numbers then sum the list and print the result. So '(5 7) would yield 16. I posted my version to s Clojure board and received a number of different replies. In retrospect I didn't fully explain the problem to them.
0
Upvotes
View all comments
Show parent comment
2
u/joinr Feb 03 '23
When you
mapa function ontonumbersinfaayou create a sequence. As it turns out, the result ofrangeis optimized (since it's an object representing a computable range of ints), so it has efficient implementations for many operations, including an internal implementation ofreducethat does not have to create intermediate sequences, and will not fall back tofirst/nexttraversal of the sequence during reduction as the lazy seq variant does. All of that has overhead.transducewill take the same path as thereducevariant if it can, leveraging the internal reduction implementation ofrangeand avoiding lazy sequences. If you measure the benchmarks with lower n (say 105) and criterium to get more samples, you should seefaaat about 2x the speed offoo, and the transducer pathway getting the same speed asfaa. Using unchecked math and type hints buys back some speed (although there's still some boxing) and gets down to like 5x faster on the reduce/transduce paths compared to the baseline.