是' for'使用像loop-recur模式一样的尾递归?

时间:2015-08-20 02:45:35

标签: clojure

传统方法:

(defn make-people [first-names last-names]
  (loop [first-names first-names last-names last-names people []]
    (if (seq first-names)
     (recur
       (rest first-names)
       (rest last-names)
       (conj people {:first (first first-names) :last (first last-names)}))
 people)))

更短的版本:

(defn shorter-make-people [first-names last-names]
  (for [[first last] (partition 2 (interleave first-names last-names))]
    {:first first :last last}))

但我现在手头没有IDE来测试大量数据的性能。

问题是:

  1. 没有'对于'做同样的事情'循环'和'复发'在这个例子中?

  2. 是否适用于更一般的案例?

  3. 建议使用任何性能测试结果。

    core.clj中的参考源代码:for loop

2 个答案:

答案 0 :(得分:3)

Warning: mysqli_stmt_bind_param(): invalid object or resource mysqli_stmt in C:\xampp\htdocs\project_procedural\php\core\login.php on line 22 PHP Warning: mysqli_stmt_bind_result(): invalid object or resource mysqli_stmt in C:\xampp\htdocs\project_procedural\php\core\login.php on line 23 PHP Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\project_procedural\php\core\login.php on line 24 PHP Warning: mysqli_stmt_close(): invalid object or resource mysqli_stmt in C:\xampp\htdocs\project_procedural\php\core\login.php on line 25 创建一个懒惰的序列,i。即它不会急切地计算for的结果。相反,它会根据需要逐步计算结果。这会增加显着的开销,并且性能比loop差(但仍然处于线性时间)。对于这个价格,延迟序列提供了不同的好处,例如处理延迟序列时,您可以选择不同时将整个序列保存在内存中。

http://clojure.org/sequences

答案 1 :(得分:1)

也许我错过了什么,但为什么会这样?在for理解的情况下,无需任何递归。

关于测试结果:

请-人

(bench (doall (make-people first-names last-names)))

Evaluation count : 1581540 in 60 samples of 26359 calls.
             Execution time mean : 40.210018 µs
    Execution time std-deviation : 1.838808 µs
   Execution time lower quantile : 37.110371 µs ( 2.5%)
   Execution time upper quantile : 44.515176 µs (97.5%)
                   Overhead used : 10.301128 ns

Found 2 outliers in 60 samples (3.3333 %)
    low-severe   2 (3.3333 %)
 Variance from outliers : 31.9497 % Variance is moderately inflated by outliers

偶数短化妆的人

(bench (doall (shorter-make-people first-names last-names)))

Evaluation count : 306180 in 60 samples of 5103 calls.
             Execution time mean : 204.226064 µs
    Execution time std-deviation : 5.726497 µs
   Execution time lower quantile : 196.693866 µs ( 2.5%)
   Execution time upper quantile : 213.226726 µs (97.5%)
                   Overhead used : 10.301128 ns

偶数短化妆的人

(defn even-shorter-make-people [first-names last-names]
  (map #(array-map :first %1 :last %2) first-names last-names))

(bench (doall (even-shorter-make-people first-names last-names)))

Evaluation count : 1049880 in 60 samples of 17498 calls.
             Execution time mean : 59.182048 µs
    Execution time std-deviation : 2.338641 µs
   Execution time lower quantile : 56.361840 µs ( 2.5%)
   Execution time upper quantile : 64.056606 µs (97.5%)
                   Overhead used : 10.301128 ns