Functional programming 函数式编程中的开销
在中,奇数整数之和达到一个极限的计算采用命令式和函数式 我将这两项分开,将上限增加到100000000000000,并对结果计时: 命令式风格:Functional programming 函数式编程中的开销,functional-programming,compiler-optimization,rust,imperative-programming,Functional Programming,Compiler Optimization,Rust,Imperative Programming,在中,奇数整数之和达到一个极限的计算采用命令式和函数式 我将这两项分开,将上限增加到100000000000000,并对结果计时: 命令式风格: 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 0
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
功能版本运行较慢,编译时间也稍长
我的问题是,是什么导致功能版本变慢?这是函数式固有的还是由于编译器没有尽可能地优化
是什么导致功能版本变慢?这是函数式固有的还是由于编译器没有尽可能地优化
通常,作为代码生成的一部分,编译器会将较高级别/较短的函数版本转换为命令式编码。它还可以应用优化来提高性能
如果编译器没有很好的优化或代码生成器,那么函数代码可能比手工编写的版本更糟糕
这完全取决于编译器。从启用优化开始。当然,您必须使用优化(rustc-O…)进行编译。功能性风格现在稍微快一点。