1

I'm reading the Akka tutorial http://doc.akka.io/docs/akka/2.5.4/scala/guide/tutorial_3.html

There's a line of code final case object ReadTemperature.

Usage of the final modifier together with object already discussed in SO here: What's the point of declaring an object as "final"? but I would like to know whether final also brings some runtime cost or not.

As far as I understand final is only relevant while compiling for overrides checks, but probably when translating to VM code there are some nuances. Would be great to hear opinions.

Alexander Arendar
  • 3,365
  • 2
  • 26
  • 38
  • As far as I know, at least for what concerns Java, there is a check that a variable is final in addition to being accessible, which tells me that final modifier is retained in java byte code. I think this check is performed regardless of whether or not a variable has final, so the performance change should be negligible. It seems reasonable to assume the same could be said also for Scala, but then, I'm not a Scala expert. – Neil Aug 30 '17 at 11:44
  • `final`, at the class level, is usually set as a declaration which says "this class cannot, and will not be extended". It's common when you develop a framework, you have to be careful what your extensible points are. – Yuval Itzchakov Aug 30 '17 at 11:47
  • You could benchmark it and bring in your results. This would benefit the community. – Michel Lemay Aug 30 '17 at 11:56
  • 2
    If any, there's probably a runtime advantage. See https://stackoverflow.com/questions/4279420/does-use-of-final-keyword-in-java-improve-the-performance – Gabriele Petronella Aug 30 '17 at 12:55

1 Answers1

3

No. Both cases are compiled down to the same output:

$ echo "case object ReadTemperature" > demo1.scala
$ scalac demo1.scala

$ javap -c ReadTemperature.class > demo1.out
$ javap -c ReadTemperature$.class > demo1$.out

$ echo "final case object ReadTemperature" > demo2.scala
$ scalac demo2.scala

$ javap -c ReadTemperature.class > demo2.out
$ javap -c ReadTemperature$.class > demo2$.out

$ diff demo1.out demo2.out
1c1
< Compiled from "demo1.scala"
---
> Compiled from "demo2.scala"

$ diff demo1$.out demo2$.out
1c1
< Compiled from "demo1.scala"
---
> Compiled from "demo2.scala"
OlivierBlanvillain
  • 7,701
  • 4
  • 32
  • 51