ActionScript - Compressing strings

Let’s suppose that you have an AIR application and you want to send some objects to a remote server. The AMF3 format used to package the data is very compact and it will save you a lot of bandwidth but if you have large strings in your objects you can save additional bandwidth by using compression. Below is a sample code that shows how to transform the strings into a ByteArray, apply compression and send them over the wire using a remote call. The Java method uncompresses the byte array and recreates the String objects.

The AS code:

   1: <mx:RemoteObject id=“SendData” destination=“SendData”/><mx:Script>
   2:     <![CDATA[
   3:         import test.Test;
   4:         import flash.utils.*;
   5:         private function send():void{
   6:              var testStrings:Array=["test data1","test data2","test data3","test data4","test data5","test data6"];
   7:              var bytes:ByteArray = new ByteArray();
   8:              for (var i:int = 0; i < testStrings.length; i++)
   9:                  bytes.writeUTF((testStrings[i]));
  10:              bytes.compress(CompressionAlgorithm.ZLIB);
  11:              SendData.sendData(bytes);
  12:         }
  13:     ]]>
  14: </mx:Script>

The Java code:

   1: public void sendData(byte[] bytes) throws Exception{
   2:
   3:     Inflater decompresser = new Inflater();
   4:     decompresser.setInput(bytes, 0, bytes.length);
   5:     byte[] result = new byte[bytes.lenght];
   6:     int resultLength = decompresser.inflate(result);
   7:     decompresser.end();
   8:
   9:     DataInputStream ddd = new DataInputStream(new ByteArrayInputStream(result,0,resultLength));
  10:     try{
  11:         while(true){
  12:             System.out.println(ddd.readUTF());
  13:         }
  14:     }catch(EOFException e){
  15:
  16:     }
  17: }

2 Responses to “ActionScript - Compressing strings”

  1. Wim Vanhenden Says:

    Hi Cornel,

    Thanks for this small but enlightening post. I was wondering, is it obliged to compress the data, or is that just for speeding up things?

    Thanks!

  2. cornel Says:

    Hi Wim,

    My opinion is that you should compress the data only if you have problems with bandwidth - so yes, for speeding up the transfer. My approach would be:

    -use amf serialization and do not care about any compression until you have a problem (bandwidth)
    -even if you have problem with bandwidth you should check if you really save a significant space by using string compression - you should be aware that also the AMF format has some optimization (the second time when the same value is found the value is not serialized - instead a reference to the first value is written). Only after testing you will know if it will make sense to use it
    -you can also try to use a http channel with gzip compression - also only by testing one can see if it’s worth-while - the CPU load vs bandwidth reduction

Leave a Reply