很难相信你可以用这种方式测量任何有意义的东西,所以这有点像猜测有多少天使可以在针头上跳舞。
有一些选项可以检查你的代码编译成什么:
apm@mara:~/tmp$ skalac -Xprint:typer angeldance.scala
[[syntax trees at end of typer]] // angeldance.scala
package angeldance {
object Main extends scala.AnyRef {
def <init>(): angeldance.Main.type = {
Main.super.<init>();
()
};
def main(args: Array[String]): Unit = {
{
val start: Long = java.this.lang.System.currentTimeMillis();
scala.this.Predef.println("took ".+(java.this.lang.System.currentTimeMillis().-(start)).+(" ms"))
};
{
val start: Long = java.this.lang.System.currentTimeMillis();
val took: Long = java.this.lang.System.currentTimeMillis().-(start);
scala.this.Predef.println(scala.StringContext.apply("took ", " ms").s(took))
}
}
}
}
在第二种情况下,StringContext.s
是 using java.lang.StringBuilder
,而在第一种情况下的表达式是 using scala/collection/mutable/StringBuilder
。这可能会导致类加载成本。你必须对它很好奇才能尝试-XX:+PrintClassLoading
。调用它作为scala -J-XX:+PrintClassLoading
.
scala> val i = 5L
i: Long = 5
scala> "hello, " + i
res0: String = hello, 5
scala> :javap -
Size 1007 bytes
MD5 checksum bbccca3ecafe9287f07df81ea123676e
Compiled from "<console>"
[snip]
8: aload_0
9: new #23 // class scala/collection/mutable/StringBuilder
12: dup
13: invokespecial #24 // Method scala/collection/mutable/StringBuilder."<init>":()V
16: ldc #26 // String hello,
18: invokevirtual #30 // Method scala/collection/mutable/StringBuilder.append:(Ljava/lang/Object;)Lscala/collection/mutable/StringBuilder;
21: getstatic #35 // Field .MODULE$:L;
24: invokevirtual #39 // Method .i:()J
27: invokestatic #45 // Method scala/runtime/BoxesRunTime.boxToLong:(J)Ljava/lang/Long;
30: invokevirtual #30 // Method scala/collection/mutable/StringBuilder.append:(Ljava/lang/Object;)Lscala/collection/mutable/StringBuilder;
33: invokevirtual #48 // Method scala/collection/mutable/StringBuilder.toString:()Ljava/lang/String;