Avoid calling length each iteration of for-each

length is O(n) so calling it should be avoided, especially for each iteration of for-each. Instead the code can just check if the first cdr is null. This has the potential for a huge speed improvement.
This commit is contained in:
Justin Ethier 2017-06-02 19:25:26 -04:00
parent 5390802816
commit aac5240a0b

View file

@ -764,7 +764,8 @@
(apply f cars)
(recur cdrs)))))
;; Fast path.
(if (eq? 1 (length lis1))
;(if (eq? 1 (length lis1))
(if (null? (cdr lis1)) ;; O(1) instead of O(n) for length
(f (car lis1))
(begin (f (car lis1))
(for-each f (cdr lis1)))))))