Skip to content

Instantly share code, notes, and snippets.

@m4kvn
Created August 13, 2019 09:12
Show Gist options
  • Select an option

  • Save m4kvn/74be38dccab61976fa65c098a3a51d2e to your computer and use it in GitHub Desktop.

Select an option

Save m4kvn/74be38dccab61976fa65c098a3a51d2e to your computer and use it in GitHub Desktop.
リソースを取得する際の処理速度について調査
package com.github.m4kvn.resource.resourceaccesstest
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updatePadding
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
class MainActivity : AppCompatActivity() {
private val texts = mutableListOf("各実行回数: $COUNT")
private val startTime = AtomicLong()
private val endTime = AtomicLong()
private val argumentText = AtomicReference<String?>()
private val text by lazy {
getString(R.string.app_name)
}
private val x1 by lazy {
resources.getDimensionPixelOffset(R.dimen.x1)
}
private val icon by lazy {
resources.getDrawable(R.drawable.ic_launcher_foreground, null)
}
private fun start(title: String, action: (Int) -> Unit) {
startTime.set(System.nanoTime())
repeat(COUNT, action)
endTime.set(System.nanoTime())
val time = (endTime.get() - startTime.get()) / 1000000
texts.add("$title\n経過時間 $time(ms)")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
start("毎回引数ありgetString") { index ->
textView.text = getString(R.string.argument_text, index)
}
start("キャッシュされた引数ありgetString") { index ->
textView.text = argumentText.get()
?: getString(R.string.argument_text, index).also {
argumentText.set(it)
}
}
start("毎回getString") {
textView.text = getString(R.string.app_name)
}
start("キャッシュされたgetString") {
textView.text = text
}
start("毎回resources.getDimensionPixel") {
textView.updatePadding(left = resources.getDimensionPixelOffset(R.dimen.x1))
}
start("キャッシュされたresources.getDimensionPixel") {
textView.updatePadding(left = x1)
}
start("毎回resources.getDrawable") {
textView.setCompoundDrawables(
resources.getDrawable(R.drawable.ic_launcher_foreground, null),
null,
null,
null
)
}
start("キャッシュされたresources.getDrawable") {
textView.setCompoundDrawables(icon, null, null, null)
}
textView.text = texts.joinToString(separator = "\n\n")
}
companion object {
private const val COUNT = 100000
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment