In AS3, do two String
s with the same value always have the same exact reference, without exception? In particular, I'm wondering if things like concatenated strings and strings returned from a web service can create duplicate instances of the same exact value.
For instance:
class Example
{
const MY_STRING:String = "Example";
.
.
.
private function myWebMethodResultHandler(pResult:ResultEvent):void
{
var myWebMethodString:String = pResult.result as String;
trace(myWebMethodString === MY_STRING); // returns true;
}
.
.
.
private function someOtherFunction():void
{
var str1:String = "Ex";
var str2:String = "ample";
var concatenatedString:String = str1 + str2;
trace(concatenatedString === MY_STRING); // returns true;
}
}
Is it absolutely guaranteed that in every case, including the ones above, that two String
s in AS3 with the same value are also the same exact instance with the same exact reference, or are there any cases at all in which String
s could be stored separately and as duplicate instances, taking up twice as much memory (and causing String
comparisons to be more complicated internally than just comparing two 32-bit references)?
That is not correct, primitive types in AS3 are not compared by reference in strict equality but by value. The strict equality by reference is reserved to complex objects. 2 string with same value will never have the same reference (this is not Python).
Now AS3 is not the only language that treats primitive differently when it comes to strict comparison and because strict equality means same reference for complex object it is normal to assume the same is true for primitives but it's not. And yes constructing the same string 5 times will result in 5 different reference and 5 different object built but this is handled efficiently in AS3 like in other languages. As mentioned a language like Python does cache primitives and in that case 2 equal string or number are likely to point to the same reference but Python in that domain is more the exception than the rule.
So to resume a bit, strict equality in AS3 can be used to check strict equality between complex objects but when it comes to primitives it has no special meaning since it only compares values which is the same as simple equality.