当函数定义如下时
static Function1<BigInteger, BigInteger> fibonacci = Function((BigInteger value) ->
value.equals(BigInteger.ZERO) ? BigInteger.ZERO
: value.equals(BigInteger.ONE) ? BigInteger.ONE
: value.equals(BigInteger.valueOf(2)) ? BigInteger.ONE
: Program.fibonacci.apply(value.subtract(BigInteger.ONE)).add(Program.fibonacci.apply(value.subtract(BigInteger.valueOf(2))))
).memoized();
并打电话
System.out.println(fibonacci.apply(BigInteger.valueOf(1000)));
计算速度非常快。但是,如果我将 memoized()
移动到函数变量,如下所示
static Function1<BigInteger, BigInteger> fibonacci = Function((BigInteger value) ->
value.equals(BigInteger.ZERO) ? BigInteger.ZERO
: value.equals(BigInteger.ONE) ? BigInteger.ONE
: value.equals(BigInteger.valueOf(2)) ? BigInteger.ONE
: Program.fibonacci.apply(value.subtract(BigInteger.ONE)).add(Program.fibonacci.apply(value.subtract(BigInteger.valueOf(2))))
); // Removed memoized() from here
并打电话
fibonacci.memoized().apply(BigInteger.valueOf(1000));
需要很长时间,就好像未应用 memoized()
一样。
这可能是什么原因?
最佳答案
因为 a) 不会在内存形式上调用递归,b) 内存的重点是您需要保存内存,而不是每次都创建新的内存。
Program.fibonacci
是根据自身定义的,因此递归调用该版本,而不是内存版本。
关于java - Vavr 的内存似乎不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47083225/