我正在寫一個函數,用於檢查兩個點在尋路算法的二維網格上是否可以看到彼此。在分析代碼後,我發現它的時間花費了60%的時間在clojure.lang.Var.getRawRoot()。爲什麼這個函數消耗了這麼多時間,我可以優化它嗎?什麼是clojure.lang.Var.getRawRoot和它爲什麼叫?
(defn line-of-sight-helper [^Maze maze [x0 y0] [x1 y1]]
"Determines if there is a line of sight from [x0 y0] to [x1 y1] in maze."
(let [dy (int (- y1 y0))
dx (int (- x1 x0))
sy (int (if (neg? dy) -1 1))
sx (int (if (neg? dx) -1 1))
dy (int (* sy dy))
dx (int (* sx dx))
bias-x (int (if (pos? sx) 0 -1))
bias-y (int (if (pos? sy) 0 -1))
x-long (boolean (>= dx dy))
[u0 u1 du su bias-u] (if x-long
[(int x0) (int x1) dx sx bias-x]
[(int y0) (int y1) dy sy bias-y])
[v0 v1 dv sv bias-v] (if x-long
[(int y0) (int y1) dy sy bias-y]
[(int x0) (int x1) dx sx bias-x])
grid (if x-long
#(blocked? maze [%1 %2])
#(blocked? maze [%2 %1]))]
(loop [u0 u0
v0 v0
error (int 0)]
(if (not= u0 u1)
(let [error (+ error dv)
too-much-error? (> error du)
next-blocked? (grid (+ u0 bias-u) (+ v0 bias-v))
branch3 (and too-much-error? (not next-blocked?))
v0 (int (if branch3
(+ v0 sv)
v0))
error (if branch3
(int (- error du))
(int error))]
(if (and too-much-error? next-blocked?)
false
(if (and (not (zero? error)) next-blocked?)
false
(if (and (zero? dv)
(grid (+ u0 bias-u)
v0)
(grid (+ u0 bias-u)
(- v0 1)))
false
(recur (int (+ u0 su))
v0
error)))))
true))))