Chromed Shark

My various ramblings about programming

Strings in AS3 and Memory

I was doing some experimenting to see whether having multiple references to a string took up much space, and it turns out that Flash doesn’t actually deep-copy strings when you copy them around. Instead it copies by reference until a change is made, which then forces a deep copy. This is similar to the way PHP works, passing strings by value but not actually creating a new object until the value is changed. Below is the code I used to determine this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import flash.system.System;
import flash.utils.ByteArray;

function clone(source:Object):* {
    var copier:ByteArray = new ByteArray();
    copier.writeObject(source);
    copier.position = 0;
    return(copier.readObject());
}

var str:String = "This is a test of string copying";
var storeA:Array = [];
var storeB:Array = [];
var before:int;

// Test A
before = System.totalMemory;
for(var i:int = 0; i < 10000; i++) {
    storeA.push(clone(str) as String);
}
trace(System.totalMemory - before); // Total Mem Increase: 3280896

// Test B
before = System.totalMemory;
for(var j:int = 0; j < 10000; j++) {
    storeB.push(str);
}
trace(System.totalMemory - before); // Total Mem Increase: 49152

// Can you change str without affecting storeB?
str = "New value";
trace(storeB[0]); // 'This is a test of string copying'

// Can you change storeB[0] without affecting storeB[1]?
storeB[0] += 'a';
trace(storeB[0]+" vs "+storeB[1]);
// 'This is a test of string copyinga vs This is a test of string copying'