Int, uint and number data type conversion

There has been a discussion in the past which data type is the fastest in AS3, or how to improve performance by using certain data types in different situations. The answer is actually very simple: performance loss occurs only when converting between data types. This is demonstrated in the loop body below, where a variable of one type is assigned to the other:

```var a:uint = 0;
var b:uint = 1 << 28;

var t:Number = getTimer();
for (var i:int = 0; i < 1e+7; i++)
{
a = b;
}
trace(getTimer() - t);
```

The loop above computes in 56ms on my machine. The same loop using only signed integers or numbers for a and b takes exactly the same time:

```//int only
var a:int = 0;
var b:int = 1 << 28;
...

//number only
var a:Number = 0;
var b:Number = 1 << 28;
...
```

Now, when var a and b is of mixed type one type has to be promoted or demoted to the other type:

```//number -> uint is ~1.8x slower
var a:uint;
var b:Number;
a = b;

//uint -> number is ~2.3x slower
var a:Number;
var b:uint;
a = b;

//number -> int is ~1.8x slower
var a:int;
var b:Number;
a = b;

//no work has to be done here
var a:Number;
var b:int;
a = b;
```

This also holds true when performing arithmetics, but not for the uint type. According to the documentation, the sum of two integers is an integer, the sum of two numbers is a number. Adding two unsigned integers needs a data type conversion first:

```//~1.2x slower
var a:uint;
var b:uint;
var c:uint = a + b;

//no difference with:
var a:int;
var b:int;
var c:int = a + b;

//or:
var a:Number;
var b:Number;
var c:Number = a + b;
```

I have chosen the value 1 << 28 because Andre Michelle posted that getQualifiedClassName() outputs different results depending on the number of bits. So in the very first code snippet with the loop body variable b seems to be of number data type:

```var b:uint = 1 << 28;
trace(getQualifiedClassName(b)) //outputs Number
```

But because the first loop performs exactly the same as the 'int to int' or 'number to number' version, a reasonable answer would be that there is something wrong with getQualifiedClassName() instead of variable b being suddenly a number.

As a rule of thumb: Avoid mixing data types, always use signed integers for everything possible (e.g. counting variables, array access..), numbers if you need precision and unsigned integers only for ARGB color values. Avoid using uints for counting variables or arithmetic expressions.

8 thoughts on “Int, uint and number data type conversion”

1. Amusingly, in AS2, using the generic Number data type, the loop takes over 26 seconds on my machine :D

2. Hi, I just discovered your weblog, and it is very interesting.

In your last paragraph, you advise only to use signed integers for ARGB colour values — but don’t you mean unsigned integers?

Thanks for you interesting posts anyway!

3. Niels you are right, I meant unsigned integers.