0

i have a frequently called methods and i want to know is there any difference between the two ways of writing

the code like this

def funA(a: Int): Unit = {
  def funB(b: Int): Int = xxx

  funB(a)
}

def funD(b: Int): Int = xxx

def funC(a: Int): Unit = {
  funD(a)
}

Will funA have different performance or memory usage than funC?

Shigure
  • 137
  • 10
  • 3
    The compiler transforms the first into the second at the bytecode level, it just ensures that such method is only accessible inside the parent method body. – Luis Miguel Mejía Suárez Apr 25 '22 at 10:14
  • 1
    @LuisMiguelMejíaSuárez Are you sure about that? `funD` is not `final` so could be overridden in a subclass whereas `funB` cannot, so I would expect the compiler to be able to optimise out `funB` but not `funD`. – Tim Apr 26 '22 at 07:02
  • This is a duplicate of https://stackoverflow.com/questions/2482326/the-cost-of-nested-methods – Erwan Daniel Apr 26 '22 at 12:05
  • Does this answer your question? [The cost of nested methods](https://stackoverflow.com/questions/2482326/the-cost-of-nested-methods) – Erwan Daniel Apr 26 '22 at 12:05
  • And note: one way to go about such things: try to measure: https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java ... the other: look at the compiled bytecode. Dont make it your first impulse to ask others to explain a new thing to you; try to dissect the thing yourself first. Do some research and analysis, and then talk to other people to see what they think about the results you came up with. – GhostCat Apr 26 '22 at 13:02

1 Answers1

2

Performance is always dependent on compiler implementation, and those threads mentioned in the comments from 12 years ago probably do not reflect current compiler behaviour.

There is, however, once clear logical difference between funB and funD which is that funD can be overridden by a subclass whereas funB cannot.

One key consequence of this is that funD cannot be optimised for tail recursion but funB can. This is one reason why recursive algorithms are often implemented using a nested function like this.

Note that this can be modified by judicious use of final and/or private on funD or the containing class, but using a nested function avoids the need for this.

Tim
  • 26,753
  • 2
  • 16
  • 29
  • 1
    In the Java world, performance mainly depends on the JVM jit implementation. And what exactly the compiler puts into the byte code ... can be seen by inspecting the bytecode. – GhostCat Apr 26 '22 at 13:07