在 Rust by Example #36 ,以命令式和函数式两种方式计算达到限制的奇数整数之和。
我将这两者分开,并将上限增加到 10000000000000000 并对结果进行计时:
命令式风格:
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
功能风格:
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
功能版本运行速度较慢,编译时间也稍长。
我的问题是,是什么原因导致功能版本变慢?这是函数式风格所固有的还是由于编译器没有尽其所能进行优化?
最佳答案
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?
通常,编译器会将较高级别/较短的功能版本转换为命令式编码,作为代码生成的一部分。它还可以应用提高性能的优化。
如果编译器优化不佳或代码生成器不佳,则功能代码可能比手动编写的版本更糟糕。
这实际上取决于编译器。首先启用优化。
关于functional-programming - 函数式编程的开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25629356/