简体   繁体   English

Ruby中的命令式与功能性编程

[英]Imperative vs Functional Programming in Ruby

I am reading this article about how to program in Ruby in Functional Style. 我正在阅读这篇关于如何在Ruby中编写功能样式的文章。 https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming

One of the examples that took my attention is the following: 引起我注意的一个例子是:

# No (mutable):
output = []
output << 1
output << 2 if i_have_to_add_two
output << 3

# Yes (immutable):
output = [1, (2 if i_have_to_add_two), 3].compact

Whereas the "mutable" option is less safe because we changing the value of the array, the inmutable one seems less efficient because it calls .compact . 虽然“mutable”选项不太安全,因为我们更改了数组的值,但是不可变的选项看起来效率较低,因为它调用了.compact That means that it has to iterate the array to return a new one without the nil's values. 这意味着它必须迭代数组以返回没有nil值的新数组。

In that case, which option is preferible? 在那种情况下,哪个选项更可取? And in general how do you choose between immutability (functional) vs performance (in the case when the imperative solution is faster)? 一般来说,如何在不变性(功能)与性能之间做出选择(在命令性解决方案更快的情况下)?

You're not wrong. 你没错。 It is often the case that a purely functional solution will be slower than a destructive one. 通常情况下,纯功能解决方案比破坏性解决方案慢。 Immutable values generally mean a lot more allocation has to go on unless the language is very well optimized for them (which Ruby isn't). 不可变值通常意味着除非语言针对它们进行了很好的优化(Ruby不是这样),否则必须继续进行更多的分配。

However, it doesn't often matter. 但是,它通常并不重要。 Worrying about the performance of specific operations is not a great use of your time 99% of the time. 担心特定操作的性能并不能很好地利用99%的时间。 Shaving off a microsecond from a piece of code that runs 100 times a second is simply not a win. 从一段每秒运行100次的代码中剔除一微秒根本不是一场胜利。

The best approach is usually to do whatever makes your code cleanest. 最好的方法通常是做任何使你的代码最干净的方法。 Very often this means taking advantage of the functional features of the language — for example, map and select instead of map! 这通常意味着利用语言的功能特性 - 例如, mapselect而不是map! and keep_if . keep_if Then, if you need to speed things up, you have a nice, clean codebase that you can make changes to without fear that your changes will make one piece of code stomp over another piece's data. 然后,如果您需要加快速度,那么您可以使用一个漂亮,干净的代码库来进行更改,而不必担心您的更改会使一段代码踩到另一块数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM