开发者

How is memory handled with javascript objects?

开发者 https://www.devze.com 2023-02-05 08:35 出处:网络
Given: Say an EventXObj is a javas开发者_运维技巧cript object that has many attributes and some methods.

Given:

Say an EventXObj is a javas开发者_运维技巧cript 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, ... ]


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号