functional-programming - 函数式编程的开销

标签 functional-programming compiler-optimization rust imperative-programming

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/

相关文章:

scala - 如何使用隐式参数实现FRP?

language-agnostic - 单子(monad)与箭头

java - Clojure 排序映射 : find largest key that is less than or equal to x (floor key)

c# - `Where` 中新对象的 Linq 查询性能

c++ - 在 g++4.4.7 中为复杂算术生成快速汇编

rust - 如何从地壳 session 中检索端口?

r - 给出函数中常见的缺失参数

c - 由 main() 修改并由 ISR() 访问的全局变量

rust - 如何构建 Rust 编译器以使用 LLVM 的自定义分支?

rust - 在 Rust 闭包中重用绑定(bind)