functional programming efficiency vs imperative

Aar*_*ron 5 javascript functional-programming

I'm new to functional programming and I just ran into something and was wondering if there was a way around this.

Suppose I have

myArray = [
  { a : 1 }
  { a : 4 }
  { a : 5 }
  { a : 6 }
  { a : 7 }
  { a : 8 }
]
Run Code Online (Sandbox Code Playgroud)

Let say I need to do statistical operations on this data set such as

const median = myArray[ Math.ceil( myArray.length / 2 ) ]['a'] // Math.ceil .. Side Effect?
const fiveOrMore = myArray.filter( value => value.a >= 5 )
const lessThanFive = myArray.filter( value => value.a < 5 )
Run Code Online (Sandbox Code Playgroud)

Some arbitrary examples. The problem with this as of right now is that with increasing amount of statistical operations I need to do, the efficiency decreases.

With imperative style, I could do everything in ONE for loop. Is this the wrong approach to functional programming that I am taking or is it a trade off of functional programming paradigm itself?

Igo*_*nko 4

这当然性能较差。性能影响您选择的风格的权衡。

有人可能会说这没什么大不了的,因为时间复杂度是O(n)唯一的区别是常数。我想说的是,请确保对您的应用程序进行性能测试。如果速度很慢,那么就该优化某些代码块了。

过早的优化是邪恶的。在很多情况下,命令式代码的运行速度比函数式代码更快或快得多,并且根据具体情况,您可能会也可能不会接受。

此外,还有多种技术可以提高性能。您不一定想改变风格。比如说,在某些情况下,记忆可以极大地提高函数的速度,同时保持代码的功能。跳出框框思考。

  • 每当你用它来谈论函数式编程时,我都会澄清“副作用”。“权衡”可能是更合适的术语。 (2认同)