我想这只是 Adobe SocketServer 的协议要求。对于单个对象,AMF 与 String 相比没有优势,因为它还对字符串使用 UTF:
package
{
import flash.display.Sprite;
import flash.utils.ByteArray;
public class astest extends Sprite
{
public function astest()
{
var str:String = "sdfKdkhsdfn345k4jhskdfhsdkf34k,,mancoasdc2";
var bytesUTF:ByteArray = new ByteArray();
bytesUTF.writeUTF(str);
var bytesAMF:ByteArray = new ByteArray();
bytesAMF.writeObject(str);
var hexUTF:String = getHexBytesString(bytesUTF);
var hexAMF:String = getHexBytesString(bytesAMF);
trace("hexUTF:", hexUTF, bytesUTF.length, "bytes");
trace("hexAMF:", hexAMF, bytesAMF.length, "bytes");
trace(hexUTF.substr(4) == hexAMF.substr(4));
}
public static function getHexBytesString(array:ByteArray, colons:Boolean=false, position:int = 0):String {
var s:String = "";
var len:uint = array.length;
for (var i:int=position;i<len;i++) {
s+=("0"+array[i].toString(16)).substr(-2,2).toUpperCase();
if (colons && i<array.length-1) s+= "-";
}
return s;
}
}
}
输出:
hexUTF: 002A7364664B646B687364666E3334356B346A68736B64666873646B6633346B2C2C6D616E636F6173646332 44 bytes
hexAMF: 06557364664B646B687364666E3334356B346A68736B64666873646B6633346B2C2C6D616E636F6173646332 44 bytes
true
但总的来说,如果您要写入两次相同的字符串,因为 AMF 使用对一个对象的 equals 字符串的引用,则AMF ( writeObject
) 与 String ( )的结果字节大小可能会有优势:writeUTF
package
{
import flash.display.Sprite;
import flash.utils.ByteArray;
public class astest extends Sprite
{
public function astest()
{
var str:String = "sdfKdkhsdfn345k4jhskdfhsdkf34k,,mancoasdc2";
var bytesUTF:ByteArray = new ByteArray();
bytesUTF.writeUTF(str);
bytesUTF.writeUTF(str);
var bytesAMF:ByteArray = new ByteArray();
bytesAMF.writeObject({str1:str, str2:str});
var hexUTF:String = getHexBytesString(bytesUTF);
var hexAMF:String = getHexBytesString(bytesAMF);
trace("hexUTF:", hexUTF, bytesUTF.length, "bytes");
trace("hexAMF:", hexAMF, bytesAMF.length, "bytes");
trace(hexUTF.substr(4) == hexAMF.substr(4));
}
public static function getHexBytesString(array:ByteArray, colons:Boolean=false, position:int = 0):String {
var s:String = "";
var len:uint = array.length;
for (var i:int=position;i<len;i++) {
s+=("0"+array[i].toString(16)).substr(-2,2).toUpperCase();
if (colons && i<array.length-1) s+= "-";
}
return s;
}
}
}
输出:
hexUTF: 002A7364664B646B687364666E3334356B346A68736B64666873646B6633346B2C2C6D616E636F6173646332002A7364664B646B687364666E3334356B346A68736B64666873646B6633346B2C2C6D616E636F6173646332 88 bytes
hexAMF: 0A0B01097374723206557364664B646B687364666E3334356B346A68736B64666873646B6633346B2C2C6D616E636F61736463320973747231060201 60 bytes
false