benchmarking imperative vs functionnal programming

51 points zarakiredchan

first time I saw this example of functional vs imperative programming,\multiply all even numbers in an array by 10 and add them all, storing the final sum in the variable "result".\\ where one is using classic for loop to calculate the result and the other one is using high order functions here is the rust code :

https://preview.redd.it/bksww75l0jy91.png?width=474&format=png&auto=webp&s=11c1a872b55bfee422c982ba7fc9f8bea5fea800

I thought the first one would be more performant, since we loop only once, and using high order functions would probably have to loop 3 times. (\filter\\, \map\\ and \reduce\\) so I created a benchmark test and the result was surprising, both have relatively the same execution time ...

test tests::bench_functional ... bench: 1,046,863 ns/iter (+/- 106,503)

test tests::bench_imperative ... bench: 1,047,672 ns/iter (+/- 52,968)

How can you explain this ? maybe I'm missing something

You can find the benchmark code here : https://github.com/rednaks/rust-move-ref-clone-bench/blob/master/src/lib.rs#L56-L89