在clojure的FizzBuzz的兩個解決方案中,爲什麼第一個更快?在clojure的FizzBuzz的兩個解決方案中,爲什麼一個更快?
; #1
(defn fizzbuzzer [z]
"fizzbuzz checker."
(let [fizz? (zero? (rem z 3))
buzz? (zero? (rem z 5))
fizzbuzz? (and fizz? buzz?)]
(cond fizzbuzz? "FizzBuzz"
buzz? "Buzz"
fizz? "Fizz"
:else z)))
; #2
(defn fizzbuzzer2 [z]
"fizzbuzz checker."
(let [fb (str
(if (zero? (rem z 3)) "Fizz" "")
(if (zero? (rem z 5)) "Buzz" ""))]
(if (seq fb) fb z)))
; profiling ;
; (time (fizzbuzzer 1500))
; => "Elapsed time: 0.098058 msecs"
; (time (fizzbuzzer2 1500))
; => "Elapsed time: 0.150438 msecs"
;; note: profiling done on separate instances to avoid caching
P. FizzBuzz?
〜如果數字可以被3整除,則打印Fizz而不是數字。如果它可以被5整除,則打印Buzz。如果它可以被3和5整除,則打印FizzBuzz。
爲什麼它更快? –