我有一个非常大的switch语句来处理来自服务器的套接字消息。目前它有一百多个案件,并将随着时间的推移而继续增长。我觉得我应该做一些比switch语句更优化的东西。我的想法: 有一个大的函数回调数组。然后,我可以简单的做这样的事情优化大型交换语句 - AS3
myArrayOfCallbacks[switchValue](parameters);
这应该把东西是O(n),其中n是开关的情况下为固定的时间正确的号码?我认为这将是一个相当不错的优化。
对不同方法的任何意见或建议?
我有一个非常大的switch语句来处理来自服务器的套接字消息。目前它有一百多个案件,并将随着时间的推移而继续增长。我觉得我应该做一些比switch语句更优化的东西。我的想法: 有一个大的函数回调数组。然后,我可以简单的做这样的事情优化大型交换语句 - AS3
myArrayOfCallbacks[switchValue](parameters);
这应该把东西是O(n),其中n是开关的情况下为固定的时间正确的号码?我认为这将是一个相当不错的优化。
对不同方法的任何意见或建议?
由于您在一个值上调用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);
所以是的,你猜对了。
我会随着客户端实现,伴随着后端。所以你将能够没有收藏。
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
是的,我总是使用开关值的地图(对象或字典)作为关键,而不是开关块时,可能。在我看来,这种方法的额外好处更具可读性。 – fsbmain