Avoid ints in ActionScript
The more I play with Flex, the more I learn, and the more I learn about ints, the less I want to use them. I’ve concluded that I’m going to stop using ints unless I really need them.
Reason 1: Numbers may actually be faster than ints
Surprising, but true. ECMAScript Edition 4 is designed to be a language that is as compatible as possible with earlier versions of ECMAScript. As it turns out, this makes it difficult to ensure that math works “correctly” in seemingly innocuous cases.
public function timingTest() : void
{
var intTime : Number;
var numberTime : Number;
var i : int;
var j : int = 0;
intTime = (new Date()).time;
for (i=0; i<10000000; i++)
j = (j + 15) / 7;
intTime = (new Date()).time - intTime;
var n : Number;
var m : Number = 0;
numberTime = (new Date()).time;
for (n=0; n<10000000; n++)
m = (m + 15) / 7;
numberTime = (new Date()).time - numberTime;
var message : String =
"int version: " + intTime + "ms\n" +
"Number version: " + numberTime + "ms";
Alert.show(message);
}
Which version do you think wins? On my machine, the int version takes 331ms, while the Number version takes 291ms. Why is this? Let’s look at the following expression:
j = (j + 15) / 7;
What happens if you start with the value j = 2^31 – 1? In some languages, you would run into overflow issues as soon as you add 15 to it. ECMAScript, however, has a looser concept of numbers. The system is supposed to move smoothly from ints to doubles as needed. Because of this, virtually all math is done internally as Number, not as int.
Given that everything is being done as a Number anyway, the extra cost of converting from int to Number and back again takes even more time, which is why the int version is slower.
There is a second counterinuitive reason for using Number over int, which is that Number actually lets you store integral values more precisely than ints do…
More »
