Вопрос

I am reading this article about how to program in Ruby in Functional Style. 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. That means that it has to iterate the array to return a new one without the nil's values.

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).

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. Shaving off a microsecond from a piece of code that runs 100 times a second is simply not a win.

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! and 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 с атрибуция
Не связан с StackOverflow
scroll top