While data compression will be a non-issue in Actionscript 3 thanks to the native compression in zlib format, every now and then the need for data compression appears on Actionscript 2 – when you want to send large amounts of user-created data to a server, for example.
Recently I had a project in which a large amount of data – around 720kb – would be sent from the Flash frontend to the server. Coming from a user-drawn image, the data was highly compressible, so I decided to compress it using LZW prior to sending to the server.
Unfortunately all LZW compression algorithms in Actionscript 2 didn’t take large amounts of data into account, so they tried to do the entire compression in one step – something that would lead to freezing the player in my case.
Because of that, I had to come up with my own LZW solution. What I came up with was an LZW class that allowed immediate LZW compression and decompression, but also allowed you to run processes in the background, while the movie execution still continued. Then the process completion could be watched by the user (by way of a percent bar) so he’d know what was going on instead of sit and wait for some mysterious computer process to complete.
This is how it looks like:
import zeh.compression.LZW; // First case: fast immediate compression, good for small strings var myString = "This is a test string"; var myCompressedString = LZW.compress(myString); // Second case: slow background compression, good for long strings var myString = "This is a test string, it should be pretty long"; var myID = LZW.slowCompress(myString); ... // Check how much is done trace ("Compression: " + (LZW.getSlowCompressFactor(myID) * 100) + "% done"); ... // Once it's finished (above function returns 1), get the final string myCompressedString = LZW.getSlowCompressString(myID); // Delete the string compression data to save memory LZW.dispose(myID);
When testing this against the other LZW classes available, it either beats most of them in speed terms, or has similar performance as the better, faster ones. The main feature is the background execution, though, which is the only reason why I needed to create my own class for this task.
Keep in mind the background execution functionality makes the compression or decompress process take a longer time, of course, but that’s what it happens when you don’t hijack the player for a single loop block anymore.