2

Or are they virtually the same? Is it better to use one or the other if I know I only need 2 pieces of information for a function?

const twoKeyValPairs = {a:1, b:2};

vs

const a = 1;
const b = 2;
BigDreamz
  • 816
  • 1
  • 7
  • 9
  • 1
    the best is to have a code that doesn't make you ashamed if others watch it – Mister Jojo Mar 08 '20 at 23:51
  • Does this answer your question? [Do object references take up extra memory?](https://stackoverflow.com/questions/16783790/do-object-references-take-up-extra-memory) – 2pha Mar 09 '20 at 00:04
  • See the second answer in the above linked question ^^ – 2pha Mar 09 '20 at 00:05
  • 1
    @2pha not really, I'm not asking about pointers to an object. I'm asking about the memory that is created with creating an object with 2 keys with ints as values vs 2 variable ints. I would assume the object takes more space, as I remember in one of my C classes, a struct took 4 or 8 bits in memory or something like that. I'm wondering if having the brackets would create a fixed space in memory, along with whatever memory the data inside creates. – BigDreamz Mar 09 '20 at 00:41
  • 1
    An object needs more housekeeping, such as its prototypes, "internal slots" and its property descriptors. Even if hidden classes are in use, they'd at least take up an extra pointer in the object header. Not to mention extra heap memory management overhead. Perhaps escape analysis and optimisations may make them equivalent, but I can't imagine an extra variable taking up *more* space than an object approach. – Jin-oh Kang Mar 09 '20 at 03:24
  • Even if both the lexical environment and objects are *somehow* backed by hash tables, more hash tables would mean more buckets, which in turn consume more memory. If you need definite answer than yoh shall use a profiler with your own JavaScript engine. – Jin-oh Kang Mar 09 '20 at 03:28

1 Answers1

0

All global variable, itself created inside an global object (window). Accessing a function variable is fast as compared to accessing key from object. You can read more from below link.

JavaScript Performance: Multiple variables or one object?

Rahul Jain
  • 369
  • 1
  • 13