Is there any way to get the memory size/usage of a variable?
Emacs 28 added a more fine-grained memory usage reporting command than was previously available:
** New command 'memory-report'.
This command opens a new buffer called "*Memory Report*" and gives a
summary of where Emacs is using memory currently.
One of its subroutines is memory-report-object-size
:
(defun memory-report-object-size (object)
"Return the size of OBJECT in bytes."
(unless memory-report--type-size
(memory-report--garbage-collect))
(memory-report--object-size (make-hash-table :test #'eq) object))
For example:
(let ((table1 (make-hash-table :size 1))
(table2 (make-hash-table :size 2)))
(mapcar #'memory-report-object-size
(list (cons nil nil)
(list nil nil)
table1
table2
(cons table1 table2)
(list table1 table2))))
;; => (16 32 32 48 96 112)