views:

69

answers:

2

I will need to handle a piano key that can respond as fast as possible without high CPU load with repetitive key press and release on virtual piano in Flex application.

Is calling function much effective or Switch?

Example:

switch(keyNote)
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;

or

function () {
if (keyNote=='c4'){keypress.button=down}
if (keyNote=='c4'){keypress.button=down}
if (keyNote=='c4'){keypress.button=down}
if (keyNote=='c4'){keypress.button=down}
}

or

function c4_Key() {
keypress.button=down;
}

I also wonder if there another method using dispatchevent to call a button by id and set button with down state?

+3  A: 

Do not go with your own if, if, if function. The compiler does not like options ( eg. if can be either true or false ) I would make a dictionary object, so that you could get the response like:

var keyMap:Dictinary = new Dictionary()
//Here you would populate the dictionary with the diff. keys and values

//pseudo body of keyDown test funcion
keyMap[keyNote].keypress.down; 

Or whatever your example code seeks to do :)

NielsBjerg
@NielsBjerg. A dictionary is somewhat more elegant than a switch (and certainly more elegant than a bunch of ifs). I'm not sure it's faster (though I also doubt any of this would be a real bottleneck). For one, the compiler builds a very compact jump table when you use a switch; I bet this is faster than an actionscript dictionary (but, as I said, the difference should be hardly noticeable).
Juan Pablo Califano
A: 

well, if you ask some OOP experts, the best thing to do is to avoid conditionals like the plague. http://www.as3dp.com/2007/12/21/lets-get-rid-of-conditionals/

The idea is that each condition is in a separate class that overrides/extends the function which would do the switch.

While I personally have not eliminated the use of conditionals in my code, I do try to use this approach over the conditionals. And you really can replace all(just about) conditionals this way, sometimes the benefit does not outweigh the work that goes into it, especially if you know that you won't be extending the code.

Daniel