こちらの記事を参考に検証してみたところ、最新バージョンだと違う結果だったので共有
https://ukaznil.com/20170902_scala_privatethis_valvar/
結果
$ sbt run
... 関係ないログは省略 ...
access with `private val` has taken 589 msec.
access with `private[this] val` has taken 576 msec.
[success] Total time: 4 s, completed 2020/04/25 10:16:45
実行コード
object Runner {
def main(args: Array[String]): Unit = {
val tester = new Tester()
tester.test()
}
}
class Tester {
private val input1 = 1234567890
private[this] val input2 = 1234567890
def test(): Unit = {
val loopNum = Int.MaxValue
val ticToc = new TicToc()
ticToc.tic()
(0 until loopNum).foreach { _ =>
val output = input1
}
ticToc.toc("access with `private val`")
ticToc.tic()
(0 until loopNum).foreach { _ =>
val output = input2
}
ticToc.toc("access with `private[this] val`")
}
}
class TicToc() {
private var started: Boolean = false
private var ticTimeInMillis: Long = 0
def tic(): Unit = {
require(!started, {
"you must call 'toc' in advance."
})
started = true
ticTimeInMillis = System.currentTimeMillis()
}
def toc(message: String): Unit = {
require(started, {
"you must call 'tic' in advance."
})
started = false
val t = System.currentTimeMillis() - ticTimeInMillis
println(s"$message has taken $t msec.")
}
}