Created
May 18, 2019 10:29
-
-
Save Mishkun/f22511060c93f0752088d7a248957e7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.benchmark | |
import androidx.benchmark.BenchmarkRule | |
import androidx.benchmark.measureRepeated | |
import androidx.test.ext.junit.runners.AndroidJUnit4 | |
import org.junit.Rule | |
import org.junit.Test | |
import org.junit.runner.RunWith | |
import kotlin.reflect.KProperty | |
/** | |
* @author themishkun on 2019-05-18. | |
*/ | |
const val keyword = "keyword" | |
@RunWith(AndroidJUnit4::class) | |
class KeywordBenchmark { | |
@get:Rule | |
val benchmarkRule = BenchmarkRule() | |
// Copy-pasted from JMH project | |
// It helps to ensure that no dead code elimination happened | |
object BlackHole { | |
var obj1: Any = Any() | |
var tlr = 1L | |
var tlrMask = System.nanoTime() | |
fun consume(obj: Any) { | |
val tlr = this.tlr | |
val tlrMask = this.tlrMask | |
this.tlr = tlr * 0x5DEECE66DL + 0xBL and 0xFFFFFFFFFFFFL | |
if (tlr and tlrMask == 0L) { | |
// SHOULD ALMOST NEVER HAPPEN IN MEASUREMENT | |
if (tlrMask != 0x7FFFFFFFFFFFFFFFL) { | |
this.tlrMask = (tlrMask shl 1) + 1 | |
} | |
this.obj1 = obj | |
} | |
} | |
} | |
@Test | |
fun getConst() { | |
benchmarkRule.measureRepeated { | |
BlackHole.consume(com.example.benchmark.keyword) | |
} | |
} | |
@Test | |
fun getVal() { | |
val keyword = "keyword" | |
benchmarkRule.measureRepeated { | |
BlackHole.consume(keyword) | |
} | |
} | |
@Test | |
fun getKeyword() { | |
val keyword by keyword | |
benchmarkRule.measureRepeated { | |
BlackHole.consume(keyword) | |
} | |
} | |
@Test | |
fun getKeywordObject() { | |
val keyword by keywordClass() | |
benchmarkRule.measureRepeated { | |
BlackHole.consume(keyword) | |
} | |
} | |
object keyword { | |
operator fun getValue(thisRef: Any?, property: KProperty<*>): String = property.name | |
} | |
class keywordClass { | |
operator fun getValue(thisRef: Any?, property: KProperty<*>): String = property.name | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment