0

Here is my code

fun main() {
val list1 = listOf("channel_name", "timestamp_us", "column_3", "column_4", "channel_name", "timestamp_us", "column_3", "column_4")
val start = System.nanoTime()
list1.joinToString(prefix = "(", postfix = ")")
val end = System.nanoTime()
print(end - start)}

And the output is much more than 1,000,000.Usually it's about 8,000,000. However,if I change my code to this:

fun main() {
val list1 = listOf("channel_name", "timestamp_us", "column_3", "column_4", "channel_name", "timestamp_us", "column_3", "column_4")
val list2 = listOf("channel_name", "timestamp_us", "column_3", "column_4", "channel_name", "timestamp_us", "column_3", "column_4")
list1.joinToString()
val start = System.nanoTime()
list2.joinToString(prefix = "(", postfix = ")")
val end = System.nanoTime()
print(end - start)}

The output usually is 15,000.

So, can anyone explain why the output of the first code is 600 times that of the second code?

My computer is MacBook Pro (16-inch, 2019),

jdk is jdk1.8.0_251,

code run in IntelliJ IDEA 2020.2.2 (Community Edition)

Kotlin plugin version is 1.4.10

马奔腾
  • 3
  • 1
  • 5
    Seems like too small a sample size to get meaningful results. Please see [Whit is microbenchmarking?](https://stackoverflow.com/questions/2842695/what-is-microbenchmarking) – Federico klez Culloca Feb 24 '21 at 13:06

1 Answers1

3

+1 to FedericoklezCulloca, it is more or less impossible (at least very hard) to have meaningful tests for cases this small. From what I can gather, the second one appears to be faster due to the JVM “warmup" phenomena, which is related to the fact that the JVM uses a dynamic compiler.

Basically, the second code gives some time to the JVM to actually compile the 2nd joinToString (the one you are measuring). While, in the first example, it might just run as interpreted code.

Btw, this is just a gut feeling, it is extremely hard to point to a single cause in microbenchmarking.

AlexT
  • 2,524
  • 1
  • 11
  • 23