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

标签 android kotlin kotlin-android-extensions kotlin-extension

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/

    相关文章:

    android editText最大限制

    java - 通过 MainActivity.java 设置我的 textView 的问题

    android - 适用于 Android 的 Kotlin : setting a Google Maps marker image to a URL

    android - 在哪里可以找到 liveData 构建 block ?

    java - java (Android) 中的 URLEncoder 编码/URLDecoder 解码

    java - Android 应用程序因方向更改而崩溃

    gradle - KotlinJS 测试不包括公共(public)类

    android - Android 性能中的 Kotlin 枚举类

    java - Android Room 在 'incoming foreign key list' 中获取 'embedded entity' 中的元素计数?

    android - 使用 Kotlin 函数特性如何使这段代码更好?