Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, will the program "remember" the result if you call the same function for the second time?

This question came up when I was thinking about the algorithm to fast compute the power of a number, say compute x^n.

In Java, the recursive part is something like:

return power(x,n/2) * power(x,n/2);

So after the program has returned the value of power(x,n/2), will it go through the whole recursive process again to compute the value for the second power(x,n/2)?

If so, should we store the value in some variable first, then return the square of that value?

like image 562
Newbie_code Avatar asked Nov 26 '11 02:11

Newbie_code


2 Answers

What you have in mind is called memoization: A pure function (i.e. a function whose return value depends only on the argument values) can remember the result for arguments that it has previously encountered.

Memoization is performed by some high-level special-purpose languages like Maple. However, general-purpose languages don't have this (rather complex) behaviour by default.

However, in your case this isn't necessary. Rather than using recursion, your algorithm is better implemented as iteration. Binary exponentiation by repeated squaring is the standard algorithm.

Here's some C-like pseudo-code (my Java isn't 100%):

// compute pow(base, exponent)

int result = 1;
int term = base;

while (exponent != 0)
{
  if (exponent % 2 != 0) { result *= term; }
  term = term * term;
  exponent /= 2;
}

return result;

For some examples, 7 is 111 in binary, so b7 = b1 × b2 × b4, and we only need to keep track of one copy of the running term. Another one: 5 = 101b, so b5 = b1 × 1 × b4.

In C++ it's quite easy to build a generic memoizing wrapper for any function R f(T1, T2, ..., TN) that stores the memory in a hash map std::unordered_map<std::tuple<T1, ..., TN>, R>; upon invocation the wrapper checks if the argument-tuple already exists, and if yes, it returns the value from the map, and if no it performs the computation and inserts the result into the map. I'm sure something similar can be rigged up in Java.

like image 88
Kerrek SB Avatar answered Oct 03 '22 07:10

Kerrek SB


In non-functional languages (where functions can (and often do) have side effects) the compiler can't know (or at least has a very hard time of knowing) whether the function will produce the same value every time.

So, the particular implementation of power might know enough to cache the value of a particular power function. (I suspect that is unlikely.) OR, a java implementation may "just know" that power works that way, and do special shortcuts with that knowledge.

Otherwise, the answer is basically "No".

like image 42
John Fisher Avatar answered Oct 03 '22 06:10

John Fisher