Array.push() Vector.push() Optimization

Actionscript:
  1. var tVerts:Vector.<Number> = new Vector.<Number>();
  2. var inc:int = 0;
  3. var t:Number, i:Number, j:Number, k:Number;
  4.  
  5.  // fast way
  6. t = getTimer();
  7. for (i= -2; i<2; i+=.03){
  8.     for (j = -2; j<2; j+=.03){
  9.         for (k = -2; k<2; k+=.03){
  10.             tVerts[inc] = i;
  11.             inc++;
  12.             tVerts[inc] = j;
  13.             inc++;
  14.             tVerts[inc]= k;
  15.             inc++;
  16.         }
  17.     }
  18. }
  19. trace(getTimer() - t);
  20.  
  21. tVerts  = new Vector.<Number>();
  22.  
  23. // slow way
  24. t = getTimer();
  25. for (i= -2; i<2; i+=.03){
  26.     for (j = -2; j<2; j+=.03){
  27.         for (k = -2; k<2; k+=.03){
  28.  
  29.             tVerts.push(i, j, k);
  30.         //  tVerts.push(j);
  31.         //  tVerts.push(k);
  32.         }
  33.     }
  34. }
  35. trace(getTimer() - t);

Today I needed to populate a Vector in the above manner... populating the vector using push() was quite slow in this case because (among other reasons) push() is a method call. I was curious how much faster populating the Vector without push would be... so I wrote this snippet - in this case it was significantly faster - took less than a third of the time. You can run this snippet to see what kind of results you get.

It's important to note that this nested for loop could be optimized further but I wanted to focus on the push() optimization alone.

Warning

The most HORRIBLE thing about testing the speed of ActionScript code is that you CANNOT rely on the debug player to test optimizations. Always use the release version of the flash player. The debug player will give unusual (usually slower) results...

This entry was posted in Vector, arrays and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted February 6, 2010 at 11:16 pm | Permalink

    tVerts.length = myVerticesCount
    will give you more speed 8)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*