2014-07-24 269 views
2

我試圖讓我的代碼更快,並且我得到了很多If-else和If-或者它。我知道,如果你有超過5個if/case的話,switch case會更快。那麼if-elseif-or有多快,它們是一樣的嗎?C#if else vs if或vs switch case

if (item.Datum.Substring(5, 5) == "06-20" || item.Datum.Substring(5, 5) == "06-21") 
{ 
    Something 
} 
else if item.Datum.Substring(5, 5) == "06-22" || item.Datum.Substring(5, 5) == "06-23") 
{ 
    Something 
} 

OR

if (item.Datum.Substring(5, 5) == "06-20") 
{ 
    Something 
} 
else if (item.Datum.Substring(5, 5) == "06-21") 
{ 
    Something 
} 
else if (item.Datum.Substring(5, 5) == "06-22") 
{ 
    Something 
} 
else if (item.Datum.Substring(5, 5) == "06-23") 
{ 
    Something 
} 

還是我剛剛與開關罩去?

switch(item.Datum.Substring(5, 5)) 
{ 
    case "06-20", "06,21": 
     Something 
     break; 
    case "06-22", "06,23": 
     Something 
     break; 
} 
+1

http://stackoverflow.com/questions/395618/is-there-any-significant-difference-between-using-if-else-and-switch-case -in-c – DarkBee

+0

[哪個更快?](http://ericlippert.com/2012/12/17/performance-rant/) –

+6

除了別的,不要多次調用Substring! –

回答

1

在某些情況下,等效的switch語句比if語句或if語句鏈慢。使用頻率啓發式,您可以在許多程序中使用if語句優化快速路徑。

看到此鏈接,你會發現兩個不同的比較

http://www.dotnetperls.com/if-switch-performance

0

我的理念時這樣一個問題彈出:少你寫越好。

爲什麼這樣的哲學?一個字:可測試性。
每次添加一行時,都必須確定其行爲已經過測試。我不特別喜歡switch synthax,但是當它將行號分成兩行時,我就採用它。

0

我會去:

dayStr = item.Datum.Substring(5, 5)) 
day = 'split '-', ',' and convert to int' 
switch day: 
{ 
    case 20: // Fall through 
    case 21: 
     // Do something 

    case 22: 
    ... 
}