gpt4 book ai didi

android - kotlin中的lazy和lazyFast有什么区别?

转载 作者:行者123 更新时间:2023-12-02 12:46:08 25 4
gpt4 key购买 nike

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 ""
}
}

最佳答案

懒惰:-

  • 它表示具有延迟初始化的值。
  • 获取当前 Lazy 实例的延迟初始化值。一旦值被初始化,它在这个 Lazy 实例的剩余生命周期内不得改变。

    • 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:-
  • 锁用于确保只有单个线程可以初始化 Lazy 实例。

  • LazyThreadSafetyMode.PUBLICATION:-
  • 在并发访问未初始化的 Lazy 实例值时,可以多次调用 Initializer 函数,但只会将第一个返回的值用作 Lazy 实例的值。

  • LazyThreadSafetyMode.NONE :-
  • 不使用锁来同步对 Lazy 实例值的访问;如果从多个线程访问实例,则其行为未定义。除非保证永远不会从多个线程初始化 Lazy 实例,否则不应使用此模式。
  • 关于android - kotlin中的lazy和lazyFast有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60521411/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com