What is the fastest way to draw pixels in AS3?
March 26th, 2008ActionScript 3 can display a dynamically generated bitmap, in which the RGB values of each pixel are computed by code. Using this capability, it is possible to render 3D scenes, process video and images, and create other effects. To draw pixels to the screen in AS3, one creates instances of the Bitmap and BitmapData classes. The BitmapData represents an array of pixels, while the Bitmap is a DisplayObject that renders those pixels. In order to draw a dynamically animated bitmap, it may be necessary to write to every pixel in the BitmapData each frame. There are at least two ways to write to all of the pixels in a BitmapData- one is to call setPixel once for every pixel, and the other is to build an appropriatedly sized ByteArray, then pass it to BitmapData.setPixels (once per frame). So, if you want your code to run as fast as possible, which should you choose? I implemented and benchmarked 8 variations of these two approaches. The code, benchmarks, and results follow.
In each test, there is an 800×600 Bitmap, showing the same simple color animation. Performance is measured in frames per second, on my MacBook with dual 2 ghz Intel core dual processors, 1 gb ram, and Safari 3.0.4.
Buffer Test 1 - 20 fps (this is the fastest)
Run Test 1 Source Code: BufferTest1.as
The fastest of the 8 implementations calls setPixels once per pixel, uses y in the outer loop and x in the inner loop, and locks and unlocks the BitmapData before and after writing to it. The main loop of code looks like this:
outputBitmapData.lock();for(y = 0; y < STAGE_HEIGHT; ++y){ for(x = 0; x < STAGE_WIDTH; ++x) { r = (t*100 + 255 * x / STAGE_WIDTH)%255; g = 180; b = 180; outputBitmapData.setPixel(x, y, (r<<16) + (g<<8) + b); }}outputBitmapData.unlock();
Before we move on to implementations using ByteArray, let us consider a few variations of the code above.
Buffer Test 6 - 20 fps (loop order doesn’t matter)
Run Test 6 Source Code: BufferTest6.as
This test is the same as test 1, except the loops iterating over x and y are interchanged, so the the outer loop is over x, and the inner loop is over y. If this were C++, I would expect this to be slower than test 1, because it writes to memory addresses that are out of order. However, it doesn’t seem to matter in AS3.
Buffer Test 7 - 9 fps (make sure to lock and unlock before setPixel)
Run Test 7 Source Code: BufferTest7.as
This test is the same as test 1, except the calls to lock and unlock are removed. It is much slower than test 1.
That wraps it up for approaches based on calling setPixel once per pixel. Now, lets look at some implementations that call setPixels once, with a ByteArray.
Buffer Test 5 - 10 to 11 fps (best ByteArray)
Run Test 5 Source Code: BufferTest5.as
This is one of the best ByteArray based implementations that I came up with. The main loop for this test looks like this:
buffer.position = 0; // buffer is a ByteArrayfor(y = 0; y < BUFFER_HEIGHT; ++y){ for(x = 0; x < BUFFER_WIDTH; ++x) { r = (t*100 + 255 * x / BUFFER_WIDTH)%255; g = 180; b = 180; buffer.writeInt( (255<<24) + (r<<16) + (g<<8) + b ); }}var rect:Rectangle = new Rectangle(0,0,BUFFER_WIDTH,BUFFER_HEIGHT);buffer.position = 0;outputBitmapData.lock();outputBitmapData.setPixels(rect, buffer);outputBitmapData.unlock();
Buffer Test 4 - 10 to 11 fps (writeInt vs writeUnsignedInt doesn’t matter)
Run Test 4 Source Code: BufferTest4.as
This is identical to test 5, except the call to writeInt is replaced with a call to writeUnsignedInt. There isn’t much change in performance here.
Buffer Test 3 - 6 fps (writeByte is SLOW)
Run Test 3 Source Code: BufferTest3.as
In tests 5, the call to writeInt effectively writes 4 bytes at once. It is also possible to call writeByte 4 times instead. Note that each 4 byte block in the ByteArray represents a pixel, in ARGB format (yes, A comes first). So this is the sequence of calls to writeByte to output 1 pixel:
buffer.writeByte(255);buffer.writeByte(r);buffer.writeByte(g);buffer.writeByte(b)
This approach is much slower than calling writeInt or writeUnsignedInt. I think this is because of the overhead of the function calls (and maybe because ByteArray is doing some internal index calculations that aren’t necessary).
Buffer Test 2 - 9 fps (ByteArray’s operator [] is fast)
Run Test 2 Source Code: BufferTest2.as
Calling readByte and writeByte is one way to get and set the data in a ByteArray, but one can also use the [] operator, which is faster. In this test, my code keeps track of the buffer offset for the current pixel / color channel (rather than in the previous tests, where this position is buffer.position, and is internally managed by ByteArray). Here’s the main loop for this test:
buffer.position = 0;var offset:int = 0;for(y = 0; y < BUFFER_HEIGHT; ++y){ for(x = 0; x < BUFFER_WIDTH; ++x) { r = (t*100 + 255 * x / BUFFER_WIDTH)%255; g = 180; b = 180; ++offset; // skip alpha channel buffer[offset++] = r; buffer[offset++] = g; buffer[offset++] = b; }}var rect:Rectangle = new Rectangle(0,0,BUFFER_WIDTH,BUFFER_HEIGHT);buffer.position = 0;outputBitmapData.lock();outputBitmapData.setPixels(rect, buffer);outputBitmapData.unlock();
Buffer Test 8 - 9 fps (locking doesn’t matter for ByteArray)
Run Test 8 Source Code: BufferTest8.as
This is identical to test 2, except that the calls to lock and unlock around the single call to setPixels are removed. The frame rate does not change, indicating that there isn’t any benefit to locking in this case. I think this is because most of the time is spent getting data into the ByteArray, not copying it into the BitmapData with setPixels.
Conclusion
The fastest way that I have found to draw pixels in AS3 is to call setPixel once for each pixel, making sure to lock and unlock before hand. If you know of a faster way, please tell me about it!
These tests imply a fairly severe upper bound on the performance that can be expected for per pixel rendering in Flash. In any real code, frame rates will be lower than those reported here, because there will be more work to do to compute the RGB values for each pixel (in these tests, the values are calculated trivially).
One of the most interesting uses of drawing pixels in AS3 is 3D rendering. As far as I know, there are a few 3D engines in AS3 that uses per-pixel drawing, including my real time ray tracer, and Away3D. On the other hand, the mainstream engines Sandy and PaperVision3D, do not rasterize into pixel buffers, but instead achieve higher performance by hacking Flash’s capabilities to draw scaled and rotated textures (which are not ideally suited for use in a 3D triangle renderer).
However, there are still other options available to make drawing pixels faster. For example, this thread on FlashKit describes a method of drawing pixels in a palletized color mode. This reduces the memory required per pixel from 4 bytes to 1 byte, but comes at the cost of restricting the number of colors on screen to 256 (+ other effects on top of that). HaXe may provide another possible avenue for accelerating per-pixel rendering in the Flash 9 virtual machine, as it is possible to program in Flash’s bytecode assembly language.
Long Term Ambien
Xanax Alprazolam Information
Drug Test Ativan Vs Xanax
Ambien Overnight No Prescriptions India
Herbal Substitutes For Xanax
Rx Cod Valium Usa
Quality Care Products Xanax
Generic Ambien Delivered Next Day
Ambien And Ingredients
Valium 5mg Pictures
Buy Xanax Online With Money Order
Does Ambien
Canin Valium
Is Restoral In The Valium Family
Filing Income Tax Tramadol
Difference Between Ultram And Tramadol
Ambien Cheap Overnight
Liver Problems From Xanax
Xanax On Airplanes
School Finance Buy Tramadol
888 557 1872 Tramadol Cod
Valium Alcool
Borderline Personality Disorder And Xanax
Order Xanax Br
Does Ambien Make You High
Xanax Tolerance
5-htp Xanax
Buy Ambien
Buy Cheap Online Tramadol
Getting Valium Of Your System
Tramadol Prescriptions
Xanax Brand Bue Pill Doseage
Ambien Neurological Effects
Valerian Valium
Buy Ambien 10mg
Methadone Maintenance And Xanax Boost
Better Sleeping Pills Other Than Ambien
Valium From Germany
Xanax Psychosis
Xanax 0 25 Mg
Help Me Stop Taking Xanax
Tramadol Percocet
Internet Prescriptions Valium
Ambien Law Suit Ohio
20 3 Profile Valium
Zyprexa Ambien Alcohol
Xanax Pharmacy
Xanax Shortness Of Breath
Drugs In Breastfeeding Tramadol
When Does Ambien Become Generic
Tramadol By Cod
Tramadol Interactions
180 Tramadol Cheap
Pharmacy Tech School Buy Tramadol
Onset Time Of Oral Xanax
Pharmacy Affiliate Programs Xanax
Memory Loss From Ambien
Iatrogenic Xanax Mortality
Natural Option For Xanax
Ambien Dosage For Date Rape
Equivalent To Valium
Xanax Overnight No Prescription
Xanax In System Drug Test
Taking Ambien And Aderall
Tramadol Package Insert
Cash Delivery Shipped Tramadol
Can You Inject Xanax
Ambien Sexual Side Effects Hard Erections
Tramadol Addiction Symptoms
Coumadin With Xanax
High Off Ambien Wikipedia
2mg Xanax No Prescribtion
Tramadol Hydrochloride Tablets
Tramadol Euphoria Pharmacy
Ativan Or Xanax
No Prescription Ambien Cr
Xanax And Drug Testing
Valium Healthy Alternative
Ambien Clinical Trial 1993
Valium With Vicodin
Debt Negotiation Buy Tramadol
Xanax Dosage Dogs
Tramadol Dog
Ambien Overdose Symptoms
Ambien 1993 Manufacturing Date
4.13 Online Purchase Xanax
Tramadol New York
Buy Diazepam Valium Without Prescription Online
Order Tramadol Online Consultation
Buy Xanax Without Prescription Overnight Delivery
Tramadol Cash Cod
Ambien Horror Stories
Tramadol Generic Ultram
Xanax Child Anxiety
Sonata Ambien And Other Sleep Aids
Ambien Pliva 563
Recovering From Xanax Addiction
Long Term Effects Ambien
Bells Palsy Valium
Buy Dream Online Pharmaceutical Tramadol Carisoprodol
Ambien Side Effects Tinnitus
Normal Valium Dose
Ambien Buy Href Profile
2737 Aid Tramadol Zyrtec
Xanax For Treatment Of Anxiety
Ambien Cr Medicine Program
Xanax Without A Prescription Us
Valium Prescription No
Ambien Withdrawals
Valium Mg Drug Store Best Prcies
Wider Xanax Bars
Taking Tramadol With Methadone
Valium Usage
Mexico Pharmacy Ambien
Ambien Medicine Sleep
Xanax Fast Delivery
Cafe Mocha Valium Myspace
Tramadol Nrop
Dr Sidney Wolfe And Valium
Tramadol Online Rx Chief
Ambien Prescription Rules
Valium Versus Zanax
Buy Ambien Online Pharmacy Online
Valium Online Price
Body Does In Long Stay Valium
Xanax From India
True Xanax Withdrawal Genuine Xanax
Buy Tramadol Cheap
Addictive Diazepam Valium And Alprazolam Xanax
Generic Ambien Price
Valiums Side Effects
Picture Of A Xanax
Tramadol Heath Solutions Network
Grapefruit And Xanax
Websites For Ambien
Xanax Withdrawal Morning
Valiums
Sizes Xanax Colors Shapes Pics
Ambien Herbal
Controversy About Ambien Cr
Valium For A Dentist Visit
Canine Tramadol Withdrawal
Kava Vs Valium
Herb Like Xanax
Ambien Oral Ingest Time
Buy Valium Online With Debit Card
Millenium Pharmacy Valium
Tramadol Twinkling Online
Ambien And Vicodin
Free Ambien Samples
Xanax No Rx Cod
Side Effects Of Xanax Alprazolam
Tramadol For Cats
Valium Alcohol Withdrawal
Cheap Xanax Free Doctor Consultation
Pauling And Rath Xanax
Xanax Overnight Cod
Symptom Withdrawal Xanax
Zoloft And Ambien Make Me Sleepy
Buspirone Vs Xanax
Buy Valium Overnight
Tramadol No Perscription
Xanax Use
Buy Cheap Xanax Online
Valium How To Take
Buy Site Tramadol
Tramadol What Is It
Roche Valium With Overnight Delivery
Ambien Available In China
Tramadol Hydrocodone
Medications That Interfere With Ambien Cr
Buy Tramadol Hcl
Valium Promotional Items
Xanax Online Fedex
Xanax Social Anxiety
Methadone And Xanax
Picture Of Tramadol Pill
Tramadol 50 Effects
Toxicology Tramadol Lethal Level
Xanax Before Pregnant
Drug Of Choice Ambien
Xanax Online Purchase Without Prescription
Grapefruit Juice Xanax
Buying Online Tramadol
Tramadol Xl
Purchase Generic Ambien Cr Online
Potassium Gates Of Neurons Function Valium
Valium For Sale
Ambien Sulfa
Hydroco Apap 500mg Xanax Interaction
Delivery Saturday Tramadol
Information Ambien
Xanax Memory
Offer Code For Ambien Cr Checks
Tramadol Recreational Drug Use
Canada Pharmacy Buy Xanax No Persciption
By Comment Tramadol
Tramadol Online Purchase
Xanax And White Blood Cell
Valium Stay In Your System
Sniffing Xanax
Valium Substitutes
Ambien Cr And Dinks
Valium Line
Colors Of Valium
Dog Medication Pain Tramadol
Xanax Kava
Crazy Ambien Behavior
Ambien And Alcohol
Tramadol Rush
Xanax Huge Discounts Xanax Overnight Delivery
Can I Take Ambien With Relpax
Xanax Deliverd Overnight No Rx Cod
Xanax Pills Pictures
Ambien Adverse Side Effects
Syncope Tramadol
Valium Without A Prescription
Tramadol 50 Mg Tablets For Dogs
Tramadol Use In Canines
Frequently Asked Questions About Xanax
Buy Without Prescription Valium
Ambien And Breast Feeding
Tramadol Vs Hydrocodone
Buy Cheap Tramadol Tramadol Ultram
Ambien Problems News
Tramadol Buzz
Ambien Cr 12.5
Ambien Medicare
Ambien Caused Loss Of Libdo
Flexeril And Xanax Unire Tests
Tramadol Cod Imitrex Diet Pill
Ambien Class Action
Ambien Goldclubmeds
Tramadol Er Dosages
Drug Testin Valium
Valium Shelf Life
Tramadol 180 Fedex
Nerve Pill Valium
Tramadol Cod
Ambien For Suicide
Overnight No Prescription Xanax
Sleep Disorder And Ambien
Ambien Street Value
Overseas Tramadol Online Pharmacy
Desk Help Software Valium
Buy Card Debit Online Phentermine Tramadol
Overnight Shipping Ambien Consultation
Ambien In The News
Buy Cheap Valium 32
Does Tramadol Work For Premature Ejaculation
Getting Xanax Xr
Name Brand Ambien Ordering
Tramadol Er
From Withdraw Xanax
Tramadol Adverse Affects
Herbal Alternatives To Xanax
Tramadol 180 3 00
Symptoms Of Intoxicated By Xanax
What S Too Much Ambien
25 Mg Xanax Effective
Tramadol Feelings Online
Ocd Tramadol Side Affects
Yellow Xanax Bars
Pharmacy Tech Resume Buy Tramadol Now
Ativan Compared To Xanax
Tramadol Hci Treatment
Buy Tramadol Now
Preparing Tramadol For Injection Erowid
Tramadol Addition
Manufacturers Of Tramadol
Xanax Online Doctor Kentucky
Tramadol Apap
Valium Without Prescription Valium
Low Cholesterol Diet Tramadol On Line
Online Purchase Tramadol
Discount Tramadol Generic Ultram
Rebates For Ambien
Public Speaking Phobia Xanax Dose
Ambien 26 Bradycardia
Delivery Flower Buy Tramadol
Xanax And Zoloft
Tramadol And Flushed Feeling
Tablet Xanax
Xanax Mastercard Ups
Valium Drug Overdose
Negative Effects Of Ambien
Xanax In China
Ambien Solubility
Overnight Shipping Of Valium
Xanax Ca
Xanax Withdrawal Symptom
What Dosages Are Available For Ambien
Valium Dental Crown
Drugs Mailorder Valium
Cyclobenzaprine Vs Valium
Man Health Tramadol On Line
Memory Loss Ambien
Ambien Vs Trazadone
Children And Ambien
Ambien Equivalent Imovane Effects Side