我有一個非常大的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