專案需求:將 20 萬筆證券數據 (10MB 文本) 載入記憶體,支援前綴匹配查詢,返回前 10 筆最佳匹配。初始實現佔用 70-80MB 記憶體,目標壓縮至 20MB 以下。
// 原始邏輯:三階段管線產生大量臨時集合
var candidates = allData.Where(x => x.Code.Contains(input) || x.Name.Contains(input)).ToList(); // 4萬對象
var scored = candidates.Select(x => new { Item = x, Score = CalculateScore(x, input) }).ToList(); // 4萬對象
var top10 = scored.OrderBy(x => x.Score).Take(10).ToList(); // 排序開銷
public class TopNSelector
{
private readonly int _capacity;
private readonly List _items = new List();
public TopNSelector(int capacity) => _capacity = capacity;
public void TryAdd(ScoredItem item)
{
if (_items.Count < _capacity)
{
_items.Add(item);
_items.Sort((a, b) => a.Score.CompareTo(b.Score)); // 升序:分數越小越優
}
else if (item.Score < _items[_capacity - 1].Score) // 優於最差
{
_items[_capacity - 1] = item;
_items.Sort((a, b) => a.Score.CompareTo(b.Score));
}
}
public IReadOnlyList GetTopN() => _items;
}
// 使用
var selector = new TopNSelector(10);
foreach (var record in allRecords) // 單次遍歷,無中間集合
{
if (Matches(record, input))
{
selector.TryAdd(new ScoredItem(record, CalculateScore(record, input)));
}
}
var results = selector.GetTopN();
效果:記憶體 80MB → 35MB,GC 壓力驟降,查詢延遲 50ms → 5ms。
// 原始:每筆記錄完整物件
class Security { string Code, Name, Pinyin, Market, Industry, ... 15欄位; }
// 僅需 4 個欄位用於搜尋:代碼、名稱、拼音、市場
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SecurityCompact
{
public int Code; // 600000 → int (4 bytes)
public int NameOffset; // 字符串池偏移
public int PinyinOffset; // 字符串池偏移
public byte MarketType; // 枚舉 byte
}
// 字符串池:所有名稱/拼音拼接為單一大字符串 + 偏移索引
// 類似 String Interning / Rope 數據結構
public class SecurityDatabase
{
public SecurityCompact[] Records; // 連續記憶體,無物件頭開銷
public string StringPool; // "浦發銀行PFYH上證A股中國石油ZGSH..."
public int[] NameOffsets; // 對應 Records[i].NameOffset
public int[] PinyinOffsets;
public int[] NameLengths;
public int[] PinyinLengths;
}
效果:17 萬筆 × (4+4+4+1) = ~2.2MB 結構體陣列 + 字符串池 ~10MB = **總計 ~12MB**。
// SecuData.h
extern "C" __declspec(dllexport) void* LoadData(const char* filePath);
extern "C" __declspec(dllexport) int Search(void* handle, const char* query, char* resultBuffer, int bufferSize);
extern "C" __declspec(dllexport) void UnloadData(void* handle);
// SecuData.cpp - 關鍵點:std::vector + 單一字符串池
// 記憶體佔用 = 原始數據大小 + 微小索引開銷 ≈ 10MB
// 查詢:二分查找 (已排序) + 字串比較,極快
public class NativeSecuritySearch : IDisposable
{
private IntPtr _handle = IntPtr.Zero;
private const string DllName = "SecuData.dll";
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr LoadData(string filePath);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern int Search(IntPtr handle, string query, StringBuilder resultBuffer, int bufferSize);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void UnloadData(IntPtr handle);
public bool Initialize(string dataFilePath)
{
_handle = LoadData(dataFilePath);
return _handle != IntPtr.Zero;
}
public string Search(string query)
{
var buffer = new StringBuilder(1024 * 10); // 10KB 緩衝區
int len = Search(_handle, query, buffer, buffer.Capacity);
return len > 0 ? buffer.ToString(0, len) : "";
}
public void Dispose()
{
if (_handle != IntPtr.Zero)
{
UnloadData(_handle);
_handle = IntPtr.Zero;
}
}
}
| 方案 | 記憶體 | 查詢延遲 | GC 壓力 | 維護成本 |
|---|---|---|---|---|
| 原始 List<Class> | 80 MB | 50 ms | 極高 | 低 |
| TopN + List<Class> | 35 MB | 5 ms | 中 | 低 |
| Struct + String Pool | 12 MB | 3 ms | 低 | 中 |
| C++ 非托管 + P/Invoke | 9 MB | 1 ms | 零 | 高 |
記憶體優化是「算法 → 資料結構 → 執行階段 → 非托管」的層層深入。大多數業務場景,**階段一+二即可達標** (10-20MB 級別)。階段三引入 C++ 互操作屬「核武器級」選項:極致效能換取極高維護成本 (編譯工具鏈、部署複雜度、除錯困難、跨平台受限)。決策前請務必以 **Profile 數據** 為準,而非直覺。