0

I've read here about the difference between functions and methods in scala. It says that methods can be slightly faster than functions. But when passing a method m as an argument using m _, m is implicitly converted to a function.

  1. Is the performance difference significant enough to ponder avoiding Functions when it is going to be a bottleneck in my program?
  2. Is there a way to pass a method as an argument without converting it to a Function?
Community
  • 1
  • 1
Guillaume Chérel
  • 1,478
  • 8
  • 17
  • It depends what your method is doing, how many arguments it has. For example if you have a method with many primitive arguments, it becomes a function, where boxig/unboxing is inevitable. As an alternative, you can create classes and pass those objects instead of Function objects. If in doubt, always measure your use case. – Gábor Bakos Jun 04 '15 at 13:30

3 Answers3

3
  1. Kind of irrelevant to by 2. But in general, forget about performance, methods are more readable than function declarations. They might be a little faster in some situations from compiler optimizations, but:

  2. You cannot pass a method as an argument without converting it to a function. A method is a special language construct, and not an object itself. You must use eta-expansion to convert it to one if you want to use it as an object.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
1
  1. No.
  2. No. In the extremely rare case where this kind of microperformance was important, you'd want to pass the object that the method is on, and either modify the receiving function to accept that, or make the object implement one of the FunctionN interfaces so that it can be used as a function.
lmm
  • 17,386
  • 3
  • 26
  • 37
0
  1. It makes just as much sense avoiding functions as it does avoiding other object allocations. There's nothing particularly special about them.

  2. It's possible to pass and invoke methods directly using reflection, but the performance is going to be much worse than passing functions in the similar situation.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487