Kotlin 的惰性委托(delegate)属性lazy 和lazyFast 有什么区别?因为它看起来像相同的代码。
private val key: String by lazy {
if (arguments != null && arguments?.getString(Constants.KEY) != null) {
return@lazy arguments?.getString(Constants.KEY).toString()
} else {
return@lazy ""
}
}
private val key: String by lazyFast {
if (arguments != null && arguments?.getString(Constants.KEY) != null) {
return@lazyFast arguments?.getString(Constants.KEY).toString()
} else {
return@lazyFast ""
}
}
最佳答案
懒惰:-
- Creates a new instance of the Lazy that uses the specified initialization function and the default thread-safety mode LazyThreadSafetyMode.SYNCHRONIZED.
- If the initialization of a value throws an exception, it will attempt to reinitialize the value at the next access.
lazy 返回一个 Lazy 对象,该对象处理 lambda 函数(initializer),根据线程执行模式(LazyThreadSafetyMode)以稍微不同的方式执行初始化。
public actual fun <T> lazy(mode: LazyThreadSafetyMode, initializer: ()
-> T): Lazy<T> =
when (mode) {
LazyThreadSafetyMode.SYNCHRONIZED -> SynchronizedLazyImpl(initializer)
LazyThreadSafetyMode.PUBLICATION -> SafePublicationLazyImpl(initializer)
LazyThreadSafetyMode.NONE -> UnsafeLazyImpl(initializer)
}
懒惰快:-
- Implementation of lazy that is not thread-safe. Useful when you know what thread you will be executing on and are not worried about synchronization.
lazyFast 还返回一个 Lazy 对象,其模式为 LazyThreadSafetyMode.NONE
fun <T> lazyFast(operation: () -> T): Lazy<T> = lazy(LazyThreadSafetyMode.NONE) {
operation()
}
LazyThreadSafetyMode.SYNCHRONIZED:-
LazyThreadSafetyMode.PUBLICATION:-
LazyThreadSafetyMode.NONE :-
关于android - kotlin中的lazy和lazyFast有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60521411/