我找不到任何关于此的信息,所以如果我问的问题已经得到回答,我深表歉意。
在编程方面,一般来说,在同一个函数中多次调用 getter 方法以达到预期的结果会更好的性能,还是应该调用一次 getter 并存储值回来了?
例如,如果我有这种方法进行二分查找:
n ← size of the array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while true
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
if getArray()[midPoint] < x
set lowerBound = midPoint + 1
if getArray()[midPoint] > x
set upperBound = midPoint - 1
if getArray()[midPoint] = x
EXIT: x found at location midPoint
end while
或者应该按如下方式存储数组:
A ← getArray()
n ← size of the array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while true
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
提前致谢!