Skip to content

Commit 4311bd0

Browse files
committed
Slightly faster hash-table-keys and hash-table-values
* lisp/emacs-lisp/subr-x.el (hash-table-keys, hash-table-values): Omit the reversal of the returned list. It is not ordered anyway. * test/lisp/emacs-lisp/subr-x-tests.el (subr-x--hash-table-keys-and-values): New test.
1 parent a203ad5 commit 4311bd0

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

lisp/emacs-lisp/subr-x.el

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,15 @@ threading."
8787

8888
(defsubst hash-table-keys (hash-table)
8989
"Return a list of keys in HASH-TABLE."
90-
(cl-loop for k being the hash-keys of hash-table collect k))
90+
(let ((keys nil))
91+
(maphash (lambda (k _) (push k keys)) hash-table)
92+
keys))
9193

9294
(defsubst hash-table-values (hash-table)
9395
"Return a list of values in HASH-TABLE."
94-
(cl-loop for v being the hash-values of hash-table collect v))
96+
(let ((values nil))
97+
(maphash (lambda (_ v) (push v values)) hash-table)
98+
values))
9599

96100
(defsubst string-empty-p (string)
97101
"Check whether STRING is empty."

test/lisp/emacs-lisp/subr-x-tests.el

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -743,6 +743,13 @@
743743
(with-current-buffer inner
744744
(should-not (buffer-modified-p))))))))
745745

746+
(ert-deftest subr-x--hash-table-keys-and-values ()
747+
(let ((h (make-hash-table)))
748+
(puthash 'a 1 h)
749+
(puthash 'c 3 h)
750+
(puthash 'b 2 h)
751+
(should (equal (sort (hash-table-keys h) #'string<) '(a b c)))
752+
(should (equal (sort (hash-table-values h) #'<) '(1 2 3)))))
746753

747754
(provide 'subr-x-tests)
748755
;;; subr-x-tests.el ends here

0 commit comments

Comments
 (0)