2

From this answer about the memory size of functions in V8 here, it seems like the minimal size of a function (excluding closures) is 36 bytes. The theoretical minimum size of a function on a 64-bit system is 8 bytes for the pointer, so: what are the other 28 bytes allocated for?

Is there a way to create "lightweight" functions in javascript? As far as I know, arrow functions aren't handled any differently from a memory perspective.

Anthony
  • 1,015
  • 8
  • 22
  • The function object needs a reference for it's `name` property, a reference to the code block at least. Oh, and a reference for the prototype chain and the constructor. – Pointy May 10 '19 at 13:24
  • @Pointy oops, yes. Edited. – Anthony May 10 '19 at 13:25
  • Okay, so the original pointer would be toward the block. I didn't even realize the prototype of functions isn't empty though. It actually has quite a bit of fields (like the name). I find it somewhat baffling that a function without the supplementary fields isn't possible, then, where it only has the name field but not length, caller, arguments, etc. – Anthony May 10 '19 at 13:32
  • Well 36 bytes is only "big" in certain programming situations. If you find yourself needing to create tens of thousands of function objects, it might be appropriate to come up with some sort of "flyweight" scheme to keep a pool of pre-created functions, or something like that. I mean, a _million_ functions is only 36 megabytes, which in 1980 was a huge amount of memory but not really so much now. – Pointy May 10 '19 at 13:34
  • That's fair. I suppose it's not a big deal, after all. Just feels unnecessarily heavy as the base. I think a flyweight object can be made by extending `Function` and deleting the properties that are considered unneeded. – Anthony May 10 '19 at 13:37
  • Or just keep a Map or simple object around to look them up. I suppose 36 bytes is a whole other thing if you're doing something like using JavaScript in a microcontroller (Raspberry Pi etc). – Pointy May 10 '19 at 13:39
  • @AnthonyMonterrosa, deleting properties isn't recommended. It won't make the object much smaller and comes with its own significant cost. Functions are objects in JS, and objects are fat in JS. You cannot do much but accept it. – Andreas Rossberg May 10 '19 at 16:43
  • @AndreasRossberg :( to WebAssembly I shall look. – Anthony May 10 '19 at 18:46

0 Answers0