You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中替代<functionReturningAList>().size的高效方案咨询

Kotlin中高效替代functionReturningAList().size的方案

你的担忧是对的——每次调用initializeList()都会创建一个全新的不可变List对象,哪怕只是为了获取size,这种重复创建对象的操作确实没必要,尤其是当sampleMethod被频繁调用时。结合你的需求(不想手动维护常量、保证性能),这里有几个实用的解决方案:

方案1:懒加载缓存初始化列表的size

利用Kotlin的lazy委托属性,让列表的size只计算一次,后续直接复用缓存值。既不用手动修改常量,又避免了重复创建列表的开销:

class Sampler {
    var sampleList = initializeList()
    
    companion object {
        // 懒加载:第一次访问时才会调用initializeList()计算size,之后直接返回缓存值
        private val INITIAL_LIST_SIZE by lazy { initializeList().size }

        private fun initializeList(): List<Int> =
            listOf(
                anObject.getNumber(1),
                anotherObject.getInt(2),
                yetAnotherObject.getInteger(3)
                // 后续添加元素时,无需手动修改INITIAL_LIST_SIZE
            )

        fun sampleMethod(numberToBeCompared: Int) {
            if (numberToBeCompared == INITIAL_LIST_SIZE) {
                println("do something")
            }
        }
    }
}

默认情况下lazy是线程安全的,适合多线程场景;如果是单线程环境,还可以用lazy(LazyThreadSafetyMode.NONE)进一步优化性能。

方案2:复用实例已有的sampleList的size

如果sampleMethod不需要留在伴生对象中,可以将其改为类的成员函数,直接复用已经初始化好的sampleList的size,完全避免重复创建列表:

class Sampler {
    var sampleList = initializeList()
    
    fun sampleMethod(numberToBeCompared: Int) {
        // 直接使用已创建的sampleList的size,无额外开销
        if (numberToBeCompared == sampleList.size) {
            println("do something")
        }
    }

    companion object {
        private fun initializeList(): List<Int> =
            listOf(
                anObject.getNumber(1),
                anotherObject.getInt(2),
                yetAnotherObject.getInteger(3)
            )
    }
}

注意:这个方案的前提是你需要判定的是当前sampleList的size(如果后续sampleList被重新赋值,size会跟着变化);如果你的需求是固定使用初始化时的列表size,那方案1更适合。

不推荐的方案:手动维护常量

虽然可以手动定义一个常量(比如private const val LIST_SIZE = 3),但正如你担心的,后续修改initializeList()的元素时,必须同步修改这个常量,很容易出错,所以不推荐这种方式。

内容的提问来源于stack exchange,提问作者Jhaycee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:55:27