user2664470
user2664470

Reputation: 801

Overhead in functional style programming

In Rust by Example #36, the sum of odd integers up to a limit is calculated in both imperative style and functional style.

I separated these two out and increased the upper limit to 10000000000000000 and timed the results:

Imperative style:

me.home:rust_by_example>time ./36_higher_order_functions_a
Find the sum of all the squared odd numbers under 10000000000000000
imperative style: 333960700851149440

real    0m2.396s
user    0m2.387s
sys 0m0.009s

Functional style:

me.home:rust_by_example>time ./36_higher_order_functions_b
Find the sum of all the squared odd numbers under 10000000000000000
functional style: 333960700851149440

real    0m5.192s
user    0m5.188s
sys 0m0.003s

The functional version runs slower and also takes very slightly longer to compile.

My question is, what causes the functional version to be slower? Is this inherent to the functional style or is it due to the compiler not optimising as well as it could?

Upvotes: 2

Views: 421

Answers (1)

Don Stewart
Don Stewart

Reputation: 137987

what causes the functional version to be slower? Is this inherent to the functional style or is it due to the compiler not optimising as well as it could?

Generally, the compiler will translate the higher level/shorter functional version to an imperative encoding as part of code generation. It may also apply optimizations that improve performance.

If the compiler has poor optimizations or a poor code generator, the functional code may be worse than manually-written versions.

It's really up to the compiler. Start by enabling optimizations.

Upvotes: 2

Related Questions