2

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:

  • Is there a performance difference in using a method in place of a function, especially since the method is internally getting converted into a function?
  • Is there a performance difference between def x:Int=10 and val x:Int=10?
  • I have read that the call-by-name parameter is actually a method which does not accept any parameter. Now, if methods are not objects, how are we using a method as a parameter value?
codingsplash
  • 4,785
  • 12
  • 51
  • 90

2 Answers2

2

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]
som-snytt
  • 39,429
  • 2
  • 47
  • 129
0

One of the differences is, val values are measured when class is loaded whilst def are measured when called.

A simple example is, say you have 100K val variables in the class (for argument's sake), the system might take long time to start. But if you have a def A in which declares 100K val. The performance will be hit only when the A is called.

Shawn Xiong
  • 470
  • 3
  • 14