Via todays post on nodename about Perlin Clouds and Frocessing I came across Ron Valstar’s AS3 version of Ken Perlin's Improved Noise reference implementation which I must have missed last year.
As Ron mentions the AS3 code runs way slower than the native perlinNoise() method that Flash's BitmapData class offers, but on the other hand his class is true to the original version and offers real 3D Perlin Noise and the possibility to control the falloff factor. So the reason for my belated post now is that I couldn't help noticing several opportunities to optimize the code. As usual optimizing will definitely not make code look better or easier to understand but for stuff like PerlinNoise which you usually called several hundred or thousand times every little counts to make it perform faster.
I attacked the class at the usual optimization points:
- Unroll functions wherever possible - this is usually the biggest timesaver. almost every function call in an inner loop is poison for execution time. The reason for that is that internally every call causes tons of save-data-on-stack and get-data-from-stack operations which do not happen if you copy the code that the function processes right into your loop.
- Do type casting whenever dealing with arrays in Flash. Especially for the indices - so instead of v = p[i+5] say v = Number( p[int(i+5)] ). That doesn't look as nice but it helps
You can see the result of this optimization here On the left is the original class, on the right the optimized one which turns out to be twice as fast. I had hoped for more but that's all I could do.
You can download OptimizedPerlin.as here or right-click the example and choose "View source".
Posted at July 11, 2008 07:04 PM | Further reading