Skip to content
This repository was archived by the owner on Jan 20, 2023. It is now read-only.

Commit 409d102

Browse files
committed
ゲッターのキャッシュを実装
1 parent 66006aa commit 409d102

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

src/main/kotlin/com/mapk/kmapper/KMapper.kt

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,23 @@ class KMapper<T : Any> private constructor(
3131
.filter { it.kind != KParameter.Kind.INSTANCE && !it.isUseDefaultArgument() }
3232
.associate { (parameterNameConverter(it.getAliasOrName()!!)) to ParameterForMap.newInstance(it) }
3333

34+
private val getCache: MutableMap<KClass<*>, List<(Any, ArgumentBucket) -> Unit>> = HashMap()
35+
3436
private fun bindArguments(argumentBucket: ArgumentBucket, src: Any) {
37+
val clazz = src::class
38+
39+
// キャッシュヒットしたら登録した内容に沿って取得処理を行う
40+
getCache[clazz]?.let { getters ->
41+
getters.forEach {
42+
it(src, argumentBucket)
43+
// 終了判定
44+
if (argumentBucket.isInitialized) return
45+
}
46+
return
47+
}
48+
49+
val tempCacheArrayList = ArrayList<(Any, ArgumentBucket) -> Unit>()
50+
3551
src::class.memberProperties.forEach outer@{ property ->
3652
// propertyが公開されていない場合は処理を行わない
3753
if (property.visibility != KVisibility.PUBLIC) return@outer
@@ -46,14 +62,19 @@ class KMapper<T : Any> private constructor(
4662
if (it is KGetterAlias) alias = it.value
4763
}
4864

49-
parameterMap[alias ?: property.name]?.let {
50-
// javaGetterを呼び出す方が高速
65+
parameterMap[alias ?: property.name]?.let { param ->
5166
javaGetter.isAccessible = true
52-
argumentBucket.putIfAbsent(it.param, javaGetter.invoke(src)?.let { value -> it.mapObject(value) })
53-
// 終了判定
54-
if (argumentBucket.isInitialized) return
67+
68+
val tempCache = { value: Any, bucket: ArgumentBucket ->
69+
// javaGetterを呼び出す方が高速
70+
bucket.putIfAbsent(param.param, javaGetter.invoke(value)?.let { param.mapObject(it) })
71+
}
72+
tempCache(src, argumentBucket)
73+
tempCacheArrayList.add(tempCache)
74+
// キャッシュの整合性を保つため、ここでは終了判定を行わない
5575
}
5676
}
77+
getCache[clazz] = tempCacheArrayList
5778
}
5879

5980
private fun bindArguments(argumentBucket: ArgumentBucket, src: Map<*, *>) {

0 commit comments

Comments
 (0)