Just another flash platform blog 

AS3 Benchmark: Ternery vs Tradional Conditionals

November 6th, 2008 Posted in General

I regularly use the ternery operator when I think it neatens up a piece of code, but recently a colleague at BBC mentioned that he thought that ternery conditional assignments are slower than regular ones. When he mentioned it I was of the opinion that it wouldn’t make a difference since the compiler would recognise both as the same thing and end up with similar bytecode.

Since then its been in the back of my mind to run some benchmarking on the two approaches to see what difference it actually makes. Before I go into the results of the heres a example of the two in case you dont know what I mean:

The regular if/else assignment:
var str:String;
if ( i%2==0 )
{
str = "true";
}
else
{
str = "false";
}

The ternery assignment:
var str:String = ( i%2==0 ) ? "true" : "false";

In the test I ran both of the above over 1,000,000 iterations and then ran each one of those tests 100 times to get a decent average. Here’s a typical result:

regular: 70.6ms
ternery: 69.5ms

As you can see very little difference. In fact I ran the same test several times and the ternery assignment always ended up slightly averagely quicker than a regular assignment. Occassionaly it was faster by as much as 10ms on average, but I think this was probably an anomally. Looking at the individual figures there was normally only 1ms in favour of the ternery.

One millisecond over one million iterations is probably not a significant difference, though if you were running such iterations frame after frame, or trying to save the world then it might be worth doing… and regarding “neatening code”, remember, neat doesnt always mean more readable so use it carefully.

I ran the tests on a Toshiba laptop, 2GB RAM and a Dual Intel 1.47 GHz, you can find the test source here. Have a go an post your results.

  • Share/Save/Bookmark
  1. 2 Responses to “AS3 Benchmark: Ternery vs Tradional Conditionals”

  2. By Mark Knol on Nov 6, 2008

    Nice test! But why would you have a boolean as string?

    I wonder if this is faster:
    var str:String = ( i%2 == 0 ).toString()

    ..than

    var str:String = ( i%2 == 0 ) ? “true” : “false”;

  3. By mattjpoole on Nov 6, 2008

    Hi Mark,

    The value being assigned to the variable is arbitury in the test it could have been a Number or a Boolean etc

    It was important to the test that both the if and the else did “something” to properly benchmark the two options. This is also why I used the ( i%2 == 0 ). This ensures that the if and the else both are evaluated the same number of times.

    This was we can be sure we are only testing the difference between the two methods of evaluating a condition.

    Though in practice your example might be quicker, it only tests an “if” rather than “if/else”

    Thanks for the comment though.

    Matt

Post a Comment