2

Is there some trade-off between these two examples of the same thing?

My bias is to always use a functional style, but if I'm running billions of these foldLefts, is creating a new FunctionalA for every step in every list less efficient than just updating a var instead?

A generic collection of values:

case class B(b: Int)
val bb = (1 to 20).toList.map(B(_))

folded imperatively:

class ImperativeA {
  var a = 0
  def ingest(x: B): Unit = a += x.b
}

val imperative_fold = 
  bb.foldLeft(new ImperativeA)((a,b) => {a ingest b; a} )

imperative_fold.a // 210

folded functionally:

class FunctionalA(val a: Int = 0) {
  def ingest(x: B) = new FunctionalA(a + x.b)
}

val functional_fold = 
  bb.foldLeft(new FunctionalA())(_ ingest _)

functional_fold.a // 210
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
kmh
  • 1,516
  • 17
  • 33
  • 3
    Is this a measure bottleneck in your application? If not, I'd favor the functional style. – Yuval Itzchakov Aug 17 '16 at 16:32
  • No bottleneck here, and either would work. My inclination is the functional approach, but I don't have a good reason why. Concurrency isn't a factor here, and it occurred to me that maybe creating billions of new objects was less elegant than just incrementing millions of vars. I'm not quite clear about how the functional version uses memory when creating a new FuctionalA for every step through bb. – kmh Aug 17 '16 at 16:54
  • 3
    You can extend your class from AnyVal, this won't allocate memory for your class. It will only create new Int's which happens in both cases. This will only work with FunctionalA/ImperativeA which contains single value(Int in this case) as this is requirement to be able to inherit from AnyVal – kpbochenek Aug 17 '16 at 17:15
  • 1
    This link here shows the relative performance of foldLeft, foreach, for loop and while loop. foldLeft turns out to be much faster for this particular test. I am a newbie to Scala but am sure there are some optimizations being done by the scala compiler for higher order functions. http://www.scalaformachinelearning.com/2013/06/comparative-performance-of-scala.html – Samar Aug 17 '16 at 17:16
  • 1
    Here is another excellent article which explores these tradeoffs in quiet a reasonable manner. https://www.sumologic.com/blog-technology/3-tips-for-writing-performant-scala/ – Samar Aug 17 '16 at 17:20

0 Answers0