You need to enable JavaScript to run this app. 编程中重复调用Getter方法与存储返回值哪种性能更优?
优惠活动
大模型
产品
解决方案
定价
更多

编程中重复调用Getter方法与存储返回值哪种性能更优?

从性能维度考量,仅调用一次getter并存储返回值后复用的实现方式明显更优,核心原因如下:

  • 规避getter的重复执行开销:不要默认getter只是简单返回类成员变量,实际开发中不少getter会包含额外逻辑:比如懒加载初始化、线程锁校验、防御性拷贝、甚至动态计算逻辑。每多调用一次getter,就会多执行一遍上述逻辑,产生无意义的性能损耗。
  • 避免循环场景的开销放大:你给出的二分查找属于循环逻辑,最差情况下需要执行O(log n)次循环,每次循环内还会调用3次getArray()。如果数组规模达到百万级别,就会产生近百次多余的getter调用,累加起来的性能差距会非常可观。
  • 降低对编译器优化的依赖:只有当编译器能100%确认getArray()没有副作用、且每次调用返回值完全一致时,才可能把多次调用优化为单次。如果getArray()的实现不在当前编译单元,或是本身存在可变逻辑,编译器不会做这类优化,你就要实打实承担多次调用的成本。

除开性能之外,单次存储返回值还能避免多线程场景下多次调用getter返回不同对象导致的逻辑错误,正确性上也更有保障。

两种实现的对照代码如下:

多次调用getter版本

n ← 数组长度
x ← 待查找的目标值

lowerBound = 1
upperBound = n 

while true
    if upperBound < lowerBound 
        退出:x不存在
   
    midPoint = lowerBound + ( upperBound - lowerBound ) / 2
      
    if getArray()[midPoint] < x
        lowerBound = midPoint + 1
         
    if getArray()[midPoint] > x
        upperBound = midPoint - 1 

    if getArray()[midPoint] = x 
        退出:x在位置midPoint被找到
end while

提前存储getter返回值版本

A ← getArray() 
n ← 数组长度
x ← 待查找的目标值

lowerBound = 1
upperBound = n 

while true
    if upperBound < lowerBound 
        退出:x不存在
   
    midPoint = lowerBound + ( upperBound - lowerBound ) / 2
      
    if A[midPoint] < x
        lowerBound = midPoint + 1
         
    if A[midPoint] > x
        upperBound = midPoint - 1 

    if A[midPoint] = x 
        退出:x在位置midPoint被找到
end while

内容的提问来源于stack exchange,提问作者Ettienne Van Zyl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 17:57:03