In java, will the program “remember” the result if you call the same function a second time?

This question arose when I thought of an algorithm to quickly calculate the power of a number, for example to calculate x^n.

In Java, the recursive part looks something like this:

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

So, after the program returns the value power(x,n/2), will it again run the entire recursive process to calculate the value for the second power(x,n/2)?

If so, should you first store the value in a variable and then return the square of that value?

+5
source share
7 answers

, , memoization: ( , ) , .

, Maple. ( ) .

. . .

C- ( Java 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;

7 111 , b 7 = b 1 & times; b 2 & times; b 4 . : 5 = 101b, b 5 = b 1 & times; 1 & times; b 4.

++ memoizing R f(T1, T2, ..., TN), - std::unordered_map<std::tuple<T1, ..., TN>, R>; , -, , , , . , - Java.

+13

( ( ) ), (, , ), .

, , . ( , .) , Java " ", .

"".

+3

. ( , ).

-, " ", , , ( "memoization" ). , .

goto10, , , , , .

+1

?

Java, , , . , JVM , :

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

 int sqrtPower = power(x, n/2);
 return sqrtPower * sqrtPower;

JVM - .

+1

, Java . JIT , , , , ( , Haskell, ).

, , , memoization . .

0

, , . , , . "" .

, ?

0

AOP.Here ,

  • , , .
  • , .
  • .
0

All Articles