~ actionscript ~

15
Jun
2006

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 »

5
Apr
2006

AS3 — on the lack of private and protected constructors

As I was talking about using objects as enums, someone made a comment about the lack of private and protected constructors. I know that the this is a sore spot, so I thought I’d explain my view of how we got here, and give my two cents.

The problem is that unlike what we did with ActionScript 2, we are working tightly with people from Mozilla and others to standardize on ECMAScript edition 4. The ECMAScript standard is not final, but we are adhering as closely as we can to the spec as it develops.
More »