str.Length == 0 或 string.IsNullOrEmpty(str) 優於 str == ""。+=。string.Format / $"" 可讀性佳,效能略低於 StringBuilder,非熱路徑可接受。
// 差:每次迴圈取 Count 屬性 (List 尚可,IEnumerable 會重新枚舉)
for (int i = 0; i < list.Count; i++) { }
// 好:預存長度
int len = list.Count;
for (int i = 0; i < len; i++) { }
// 避免在迴圈呼叫方法 (內聯較佳)
foreach (var item in list) { DoWork(item); } // JIT 可能內聯
List、Dictionary 取代 ArrayList/Hashtable。where T : struct 或避免 value type 傳入 object。StringBuilder、MemoryStream、SocketAsyncEventArgs。new 大型陣列/物件圖。throw ex; (會重設堆疊),用 throw;。| 項目 | 建議 | 影響 |
|---|---|---|
| ViewState | 不需要的控制項 EnableViewState="false";整頁關閉或改用 Session/ClientState |
減少頁面大小 20-50% |
| Server.Transfer vs Response.Redirect | 同站內跳轉用 Server.Transfer (避免 302 往返),但 URL 不變、瀏覽器歷史不同步 |
少一次 HTTP 往返 |
| 控制項選擇 | Repeater > ListView > GridView/DataList (輸出最輕量) | Render 時間、ViewState 大小 |
| 輸出快取 | <%@ OutputCache Duration="60" VaryByParam="id" %> 靜態/半靜態頁 |
CPU 大幅下降 |
| 資料快取 | MemoryCache / Redis 快取熱門查詢、字典表 |
DB 壓力降低 80%+ |
| 壓縮 | IIS 動態/靜態壓縮 (gzip/deflate/br) | 傳輸量 -70% |
| Client 端快取 | 靜態資源 Cache-Control: max-age=31536000 + 指紋版本 |
回訪零請求 |
using (var cn = new SqlConnection(cs)) { cn.Open(); ... } 確保釋放。Max Pool Size=512; Min Pool Size=10; (高併發)。OFFSET/FETCH (SQL 2012+) 或 ROW_NUMBER。// 最快:序數 + 強型別 Get 方法
int ordId = reader.GetOrdinal("Id");
int ordName = reader.GetOrdinal("Name");
while (reader.Read())
{
int id = reader.GetInt32(ordId);
string name = reader.GetString(ordName);
// ...
}
reader.Close();
效能排序:GetInt32(ord) > GetInt32("Name") > reader["Name"] > reader[0] (後兩者需查找/裝箱)。
public async Task> GetProductsAsync()
{
using (var cn = new SqlConnection(cs))
using (var cmd = new SqlCommand(sql, cn))
{
await cn.OpenAsync();
using (var reader = await cmd.ExecuteReaderAsync())
{
var list = new List();
while (await reader.ReadAsync())
list.Add(Map(reader));
return list;
}
}
}
釋放執行緒處理更多並發請求,提升吞吐量。
[ ] 移除 Debug="true" (web.config compilation)
[ ] 啟用 IIS 動態/靜態壓縮
[ ] 靜態資源設定長效快取 + 版本指紋
[ ] 關閉不需要的 ViewState
[ ] 關鍵查詢加上索引、避免 SELECT *
[ ] 連線字串 Max Pool Size 適當調大
[ ] 熱門資料加入 MemoryCache/Redis
[ ] 大檔案下載用 TransmitFile/FileStreamResult
[ ] 錯誤頁面不洩露堆疊資訊 (customErrors mode="RemoteOnly")
[ ] 啟用 HSTS、CSP、X-Frame-Options 等安全標頭