核心優化原則
- 避免裝箱/拆箱:改用泛型集合 (
List<T>) 取代 ArrayList。.NET 2.0+ 泛型消除 object 轉型開銷。
- 字典選擇:少量資料首選
Dictionary<TKey, TValue> 或 Hashtable,避免 StringDictionary 等舊型別。
- 字串常數化:將重複字串常值提升為
const string 或 static readonly,減少記憶體配置。
- 字串比較:使用
String.Compare(strA, strB, true) (忽略大小寫) 取代 ToUpper()/ToLower() 產生暫時字串。
- StringBuilder 取代 + 串接:迴圈或多次串接務必用
StringBuilder,避免產生大量暫時字串物件。
- 唯讀 XML 用 XPathDocument:
XPathDocument + XPathNavigator 效能優於 XmlDocument,因無 DOM 樹維護開銷。
- 迴圈外宣告變數:將物件宣告移至迴圈外,迴圈內僅重新指派,減少堆疊配置頻率。
- 精確捕捉例外:捕捉具體例外型別 (
NullReferenceException) 而非 Exception,避免隱藏錯誤並提升效能。
- finally 釋放資源:資料庫連線、檔案流、網路通訊埠必須在
finally 區塊釋放,確保異常時亦能清理。
- 避免遞迴與深層巢狀迴圈:改用迭代演算法或資料結構 (佇列/堆疊) 實作,防止堆疊溢位與效能指數級下降。
- 善用快取策略:
MemoryCache、HttpRuntime.Cache、輸出快取等,減少重複運算與 I/O。
程式碼對照示範
❌ 不佳 vs ✅ 建議
// 字串串接
// ❌
string xml = "<root>";
xml += "<item>" + value + "</item>";
xml += "</root>";
// ✅
var sb = new StringBuilder();
sb.Append("<root>");
sb.Append("<item>").Append(value).Append("</item>");
sb.Append("</root>");
string xml = sb.ToString();
// 字串比較
// ❌
if (str.ToUpper() == "ABC") ...
// ✅
if (String.Compare(str, "ABC", true) == 0) ...
// 資源釋放
// ✅ 模式
var conn = new SqlConnection(cs);
try { conn.Open(); ... }
finally { conn.Close(); } // 或 using 區塊