优化大型交换机声明 - AS3

时间:2014-03-26 08:41:10

标签: actionscript-3 optimization switch-statement

我有一个非常大的switch语句,用于处理来自服务器的套接字消息。它目前有100多个案例,并将继续增长。我觉得我应该做一些比switch语句更优化的东西。

我的想法: 有大量的函数回调。然后我可以简单地做一些像

这样的事情
myArrayOfCallbacks[switchValue](parameters);

这应该是O(n)的东西,其中n是开关案例的数量到正常的时间吗?我认为这将是一个非常好的优化。

对不同方法的任何意见或建议?

2 个答案:

答案 0 :(得分:2)

我会选择伴随后端的客户端实现。所以你可以没有收藏。

if (eventType in responseController) {
    //Before call, you could do secure checks, fallbacks, logging, etc.
    responseController[eventType](data);
}

//Where eventType is 'method' name, 
//for example command from the socket server is 'auth',
//if you have implemented method `auth` in your responseController
//it will be called

答案 1 :(得分:1)

由于您在一个值上调用switch-case,因此最好将可能的值排列成可能值的静态数组,并获得另一个要调用的相应函数的静态数组。那你就是这样的:

public static const possibleValues:Array=['one value','two value',...];
// in case of ints, use only the second array
public static const callbacks:Array=[oneFunction,twoFunction,...];
// make sure functions are uniform on parameters! You can use 1 parameter "message" as is
...
var swtichValue=message.type; // "message" is an Object representing the message
// with all its contents
var callbackIndex:int=possibleValues.indexOf(switchValue);
if (callbackIndex>=0) if (callbacks[callbackIndex]) callbacks[callbackIndex](message);

所以是的,你猜对了。