Basically sizeof for lists, hashmaps, etc., with nested structures.

I could of course disable garbage collection and then compare numbers from memory usage functions before and after allocation, getting vaguely informative but imprecise numbers—due to probably also having created intermediate vars.

But maybe there's a method that involves less approximate guesswork and more straightforward calculation?


Is there any way to get the memory size/usage of a variable?

Emacs 28 adds 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--object-size (make-hash-table :test #'eq) object))

For example:

(let ((table (make-hash-table)))
  (mapcar #'memory-report-object-size
          (list (cons nil nil)
                (list nil nil)
                (cons table table)
                (list table table))))
;; => (16 32 1056 1072 1088)
  • Interesting. I have to wonder now if 28 also changes memory usage of any types. – aaa May 10 at 0:18
  • From the first two we can infer that a cons cell requires 16 bytes and nil values 0 (cons + 2nil = 16; 2cons + 3 nil = 32). – D. Ben Knoble May 10 at 13:45
  • @D.BenKnoble It's common in many Lisp implementations for nil to be implemented as an immediate value, so it doesn't take any space itself. – Barmar May 10 at 15:11
  • And this is also true for fixnums. – Barmar May 10 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.