为什么这段代码不会抛出StackOverflow异常 [英] Why this code does not throw StackOverflow exception
本文介绍了为什么这段代码不会抛出StackOverflow异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在clojure v1.6.0中,此代码只会永远运行,并消耗一个核心的100%:
xy](/(+ xy)2))
/ pre>
(defn improve [guess x]
(平均猜测(/ x猜)))
sqrt-iter [guess x]
(sqrt-iter(improve guess x)x))
(sqrt-iter 1 4)
我希望它立即引发一个
StackOverflowError
,但它不会。
解释为什么会发生?
解决方案代码开始计算极长的理性值,并且在经过几次迭代之后缓慢爬行。如果你用1.0和4运行它,它在几千次调用后会非常迅速地打击(根据你的jvm参数可能会有所不同)。
In clojure v1.6.0, this code just runs forever and consumes 100% of one core:
(defn average [x y] (/ (+ x y) 2)) (defn improve [guess x] (average guess (/ x guess))) (defn sqrt-iter [guess x] (sqrt-iter (improve guess x) x)) (sqrt-iter 1 4)
I'd expect it to throw a
StackOverflowError
immediately, but it doesn't.Any explanation why it happens?
解决方案Because 1 is a long. The code starts computing extremely long rationals, and slows to a crawl after a few iterations. If you run it with 1.0 and 4 it blows the stack very quickly after a few thousand calls (may vary depending on your jvm parameters).
这篇关于为什么这段代码不会抛出StackOverflow异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文