原文地址:http://bbs.9ria.com/viewthread.php?tid=122274
如果要写网络编程接口的话,解码、编码,有时候我们会经常的对ByteArray临时变量的使用,
之前对AS3 不了解,看了看网上一些网友写的都是直接new一个新的ByteArray来初始,但性能巨损,后来发现,ByteArray的.length=0;可以直接清空数据,而且效率不是一般的高。
测试结果如下:
对200 mb 的数据裁剪:
package { import flash.display.Sprite; import flash.utils.ByteArray; import flash.utils.getTimer; /** * 巨量字节裁剪器测试 * @author Jave.Lin */ public class LargeByteArrayCutterTest extends Sprite { public function LargeByteArrayCutterTest() { super(); var startTime:int=getTimer(); var sourceByteArray:ByteArray=new ByteArray(); //209715200==200mb=200*1024*1024==2亿多 var rate:int=0; for (var i:int = 0; i < 209715200; i++) { rate=(i/209715200)*255; sourceByteArray.writeByte(rate); } trace("create sourceByteArray.length",sourceByteArray.length," use time:",getTimer()-startTime); var transformByteArray:ByteArray=new ByteArray(); var startIndex:int=209715200/3; var endIndex:int=209715200-(209715200/3); var cutedLen:int=endIndex-startIndex; var loopCount:int=cutedLen/68000; var perCutLen:int=10*1024;//每次10kb var useIndex:int=startIndex; startTime=getTimer(); sourceByteArray.position=startIndex; for (var j:int = 0; j < loopCount; j++) { //高效初始化方法,不要用new transformByteArray.position=0; transformByteArray.length=0; sourceByteArray.readBytes(transformByteArray,0,perCutLen); } trace("cuted len",cutedLen," use time:",getTimer()-startTime); trace("cuted len:",cutedLen); trace("startIndex:",startIndex); trace("endIndex:",endIndex); startTime=getTimer(); transformByteArray.position=0; transformByteArray.length=0; sourceByteArray.readBytes(transformByteArray,sourceByteArray.position,sourceByteArray.length-endIndex); sourceByteArray.position=startIndex; sourceByteArray.writeBytes(transformByteArray,0,transformByteArray.length); sourceByteArray.length-=cutedLen; trace("writed len:",cutedLen," use time:",getTimer()-startTime); trace("sourceByteArray.length",sourceByteArray.length); /* 输出情况: create sourceByteArray.length 209715200 use time: 39118//构造209715200 个字节的数据用时:39118 毫秒 cuted len 69905067 use time: 60//切69905067 个字节的数据用时:60毫秒 startIndex: 69905066//开始切入点:69905066 endIndex: 139810133//终始切入点:139810133 writed len: 69905067 use time: 130//写69905067 个字节的数据用时:130 sourceByteArray.length 150336852//构造数据最终长度为:150336852个字节 */ } } }