先說結論 : Switch case 再Case數量 > 5 之後比 if else 還快 ( 但快非常少 )
為什麼? 他經過什麼轉換?
Switch Case 是語法糖 所以他會經過轉換 基本上就是轉成 if else 的形式 只是會做一些優化處理
以下為轉換程式碼
如果 case 是數字常數時->會轉成樹狀查詢
轉成:
物件格式:
結論: 當switch case 是數字常數時會比較快 or 非數字常數要超過5個以上才會優化
參考:
先說結論 : Switch case 再Case數量 > 5 之後比 if else 還快 ( 但快非常少 )
為什麼? 他經過什麼轉換?
Switch Case 是語法糖 所以他會經過轉換 基本上就是轉成 if else 的形式 只是會做一些優化處理
以下為轉換程式碼
如果 case 是數字常數時->會轉成樹狀查詢
int a = 100; |
轉成:
int num = 100; |
物件格式:
Object b = "100"; |
| case 數量 >5 時 會先轉HashCode 所以能夠被樹狀查詢 ( 會比較快點 ) 轉成: |
object obj = "100"; |
結論: 當switch case 是數字常數時會比較快 or 非數字常數要超過5個以上才會優化
參考:
Array & List 常常要做 null check & out of range check 寫起來麻煩 把這段寫成擴充函式方便些
public static class ArraySafe
{
public static bool IsSafe<T>(this T[] array, int index)
{
return array != null && index >= 0 && index < array.Length;
}
public static bool IsSafe<T>(this System.Collections.Generic.List<T> array, int index)
{
return array != null && index >= 0 && index < array.Count;
}
public static bool TryGetElement<T>(this T[] array, int index, out T element)
{
if (array == null || index < 0 || index >= array.Length)
{
element = default(T);
return false;
}
element = array[index];
return true;
}
public static bool TryGetElement<T>(this System.Collections.Generic.List<T> list, int index, out T element)
{
if (list == null || index < 0 || index >= list.Count)
{
element = default(T);
return false;
}
element = list[index];
return true;
}
}