0

How does Javascript allocates memory for strings? I ran this simple code in chrome:

var s = 'a';
var i;
for (i = 0; i < 5000000; i++) {
    s += 'b';
}

var s2 = s;
s2[4000000] = 'a';

and attached Windbg to chrome, added conditional breakpoint in HeapAlloc, VirtualAlloc, and VirtualAllocEx with condition "requested bytes parameter > 4.5M". when the above code ran I didn't see any such big allocation in the debugger.
I expected that at least for s2 I'll see such allocation.

elad-ep
  • 333
  • 1
  • 9

1 Answers1

0

when the above code ran I didn't see any such big allocation in the debugger.

Here s += 'b'; has static string 'b'. It is very likely that string intering is at play.

Try making these random strings or perhaps numbers as strings.

I expected that at least for s2 I'll see such allocation.

Here s2 is just a reference i.e.not creating more allocation. Try copying the whole array.

Community
  • 1
  • 1
bhantol
  • 9,368
  • 7
  • 44
  • 81
  • I tried with ArrayBuffer as well, no success - I don't see the memory allocations I expected: `var a = new ArrayBuffer(9000000); var view = new Int8Array(a); for(var i = 0; i – elad-ep Jan 04 '17 at 08:51