b_dev
b_dev

Reputation: 2598

How is memory handled with javascript objects?

Given:

Say an EventXObj is a javascript object that has many attributes and some methods.

An EventXObj can be associated to a simple string id as follows.

[ "id1" : Event1Obj , "id2": Event2Obj, ..., "id1000": Event1000Obj ]

And we want to represent how a single PlaceXObject can hold many events.

THE QUESTION:

In regards to below, does Scenario A take much more memory than Scenario B?

Scenario A

PlaceX.events = [ "id1", "id2", "id75", ... ]

Scenario B

PlaceX.events = [ Event1Obj, Event2Obj, Event75Obj, ... ]

Upvotes: 4

Views: 240

Answers (2)

jweyrich
jweyrich

Reputation: 32260

It depends exclusively on the memory model used by the JavaScript engine you're using.

Taking the current version of V8 as example (assuming 32 bit):

  • Pointers = 4 bytes.
  • Strings = 12 + [string length] bytes.
  • Concatenated strings = 12 + 2 * 4 bytes (2 * 4 because it's a pair of pointers to existing strings). However, you can force flat-strings if you want.
  • Dictionary with n elements = 3 * 4 * 2 * closestPowerOfTwo(n) bytes.

Now you're able to do the math for the current version of V8.

Upvotes: 2

Jakob
Jakob

Reputation: 24370

Scenario B is probably the most memory efficient one from a generic perspective. Everything in JavaScript is like a pointer/reference, so B uses a single integer (or so) for each event that is contained in your array.

Scenario A uses as much memory as your strings does, so for long string it would be bad. For your case, with very short strings, there is not much difference though.

Upvotes: 2

Related Questions