JavaScript Memory – Memory Needed to Store a Function in JavaScript

functionsjavascriptmemory

I have been using sizeof.js to investigate the size of various objects in javascript. It appears from this that the size of a function is essentially zero bytes, regardless of how many instructions the function executes. Why is this so?

Best Answer

In most languages, code and data are different things. They occupy different parts of memory and don't interact with each other.

When you ask the code "how big is this" you are asking about "how big is the instantiated object". When looking at this you through tools like sizeof.js, you are asking the question "how big is the object representing the function pointer". And in this case, the object doesn't have any additional properties its size is negligible.

Asking how big something in a language like javascript which is often not compiled down too far becomes one of "how big is this parse tree", which doesn't have any real meaning at runtime... nor is it always accessible.

Some languages such as Lisp, where the data and code can mix a bit more freely (the code is data), such a question can be slightly more meaningful, though not really. While I'm sure if I fought with it long enough (my lisp is a bit rusty and I never delved into that realm of lisp metaprogramming), I could come up with:

(defun double (x) (* x 2))

(print (somefunc 'double))

such that it would print out a value of 2, or 4 depending on how you wanted to define that. But it's not a meaningful number in most cases.

Nor is the "how big is that function?" question asked of a javascript function pointer. It is. And whats more, under different javascript engines, if you could get a number, it would likely be different.

So:

  • The question you are asking of sizeof.js is giving you back the right number.
  • The object that represents the function pointer has no appreciable size associated with it.
  • Hypothetically, it could have data that wasn't the code associated with it and you would get back a different number.
  • The code lives in a different spot in memory than the data that sizeof.js may not have a way to access.
  • The size of the code isn't a meaningful number within the runtime.