我有一个非常大的开关语句,它处理来自服务器的套接字消息。它目前有100多个病例,并将继续增长。我觉得我应该做一些比开关语句更优化的事情。
我的想法是:拥有大量的函数回调。然后我就可以做一些简单的事情
myArrayOfCallbacks[switchValue](parameters);这应该会把O(n)的东西,其中n是开关的数目,变成恒定的时间,对吗?我认为这将是一个很好的优化。
对另一种方法有什么意见或建议吗?
发布于 2014-03-26 08:57:02
因为要对一个值调用一个开关大小写,所以最好将可能的值安排为一个可能值的静态数组,然后调用另一个相应函数的静态数组。那你就像这样:
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);所以是的,你猜得很对。
发布于 2014-03-26 17:00:19
我会与客户意识到,伴随后端。这样你就可以不用收藏了。
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 calledhttps://stackoverflow.com/questions/22655461
复制相似问题