0

I couldn't find anything regarding this so if I'm asking a question already answered I apologise.

When it comes to programming, in general, would it be better performance-wise to call a getter method a couple of times in the same function to achieve the desired outcome, or should one rather call the getter once and store the value it returned?

For example, if I have this method to do a binary search:

   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

Or should it rather store the array as follows:

   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

Thanks in advance!

Code Adapted From TotorialsPoint

  • [This answer](https://stackoverflow.com/a/19445786/7389264) to a similar question gives a useful answer: using local variables is probably better for readability. In specific usages and languages, it may also be more performant, especially if the method is computationally expensive. – jirassimok Jun 02 '21 at 23:54
  • [Here](https://stackoverflow.com/a/1923866/) is another useful answer to another similar question. Despite being written specifically about Java, the same ideas broadly apply in general. – jirassimok Jun 03 '21 at 00:02
  • @jirassimok thank you for your comments, both links provide good reasons but your first comment's linked answer was more useful to me. Thanks again. – Ettienne Van Zyl Jun 03 '21 at 09:36

0 Answers0