Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance memory safety with HybridPriorityQueue. #34

Merged
merged 1 commit into from
Jan 26, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions Megrez/src/0_CSharpExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ public EnumeratedItem(int offset, T value) {
/// <summary>
/// 針對 Sandy Bridge 架構最佳化的混合優先佇列實作。
/// </summary>
public class HybridPriorityQueue<T>
where T : IComparable<T> {
public class HybridPriorityQueue<T> : IDisposable where T : IComparable<T> {
// 考慮 Sandy Bridge 的 L1 快取大小,調整閾值以符合 32KB L1D 快取行為。
private const int ArrayThreshold = 12; // 增加閾值以更好地利用快取行。
private const int InitialCapacity = 16; // 預設容量設為 2 的冪次以優化記憶體對齊。
Expand Down Expand Up @@ -223,10 +222,15 @@ private int FindInsertionPoint(T element) {
}

private void SwitchToHeap() {
_usingArray = false;
// 就地轉換為堆積,使用更有效率的方式。
for (int i = (_count >> 1) - 1; i >= 0; i--) {
HeapifyDown(i);
try {
_usingArray = false;
// 就地轉換為堆積,使用更有效率的方式。
for (int i = (_count >> 1) - 1; i >= 0; i--) {
HeapifyDown(i);
}
} catch {
Clear(); // 確保發生異常時也能清理。
throw;
}
}

Expand Down Expand Up @@ -283,6 +287,12 @@ public void Clear() {
if (_storage.Length > InitialCapacity) {
_storage = new T[InitialCapacity];
}
Array.Clear(_storage, 0, _storage.Length); // 清除所有參考
}

public void Dispose() {
Clear();
_storage = null;
}
}
} // namespace Megrez
Loading