scalacallbyname

Performance difference between def and val


Consider the below code where I am passing a method and a function as a parameter to map()

  val list1:List[Int]=List(10,20,30)

  def func1(x:Int):Int={
      x+10
  }

  list1.map(func1)
  list1.map(_+10)

I have few questions about ETA expansion:


Solution

  • There is no significant difference between the expressions you're asking about.

    val x incurs a private field.

    Note that vs.map(_+10) inlines the function, as compared to vs.map(x => f(x)). But you have to create a function object in any case.

    A call-by-name argument => X is a () => X under the hood.

    From the REPL, use javap to show code. -c for code, -v for verbose.

    scala> vs.map(f)
    res0: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
    
    scala> :javap -pv -
    [snip]