Commit 2fc4420
committed
fix(memory): add GC memory pressure tracking for unmanaged allocations
Fixes GitHub issue #501 where memory would grow to 10GB+ when creating
many NDArrays in a loop without explicit GC.Collect() calls.
Root cause: NumSharp allocates data via NativeMemory.Alloc (unmanaged)
but did not inform the GC about this memory pressure. The GC only saw
small managed objects (~100 bytes each) and didn't know about the
~880+ bytes of unmanaged data per array, so it would not trigger
collections frequently enough.
Fix: Add GC.AddMemoryPressure() when allocating unmanaged memory and
GC.RemoveMemoryPressure() when freeing it. This informs the GC about
the true memory footprint so it schedules collections appropriately.
Before fix: Creating 1M arrays with 110 doubles each peaked at 10+ GB
After fix: Same workload peaks at ~54 MB (stable, proper GC behavior)
Changes:
- Disposer constructor now takes bytesCount parameter for Native allocs
- Call GC.AddMemoryPressure(bytesCount) on allocation
- Call GC.RemoveMemoryPressure(bytesCount) on deallocation1 parent 3cb8eca commit 2fc4420
1 file changed
Lines changed: 14 additions & 3 deletions
Lines changed: 14 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
29 | 29 | | |
30 | 30 | | |
31 | 31 | | |
32 | | - | |
| 32 | + | |
33 | 33 | | |
34 | 34 | | |
35 | 35 | | |
| |||
984 | 984 | | |
985 | 985 | | |
986 | 986 | | |
| 987 | + | |
987 | 988 | | |
988 | 989 | | |
989 | 990 | | |
990 | 991 | | |
991 | 992 | | |
992 | | - | |
993 | | - | |
| 993 | + | |
| 994 | + | |
| 995 | + | |
994 | 996 | | |
995 | 997 | | |
| 998 | + | |
996 | 999 | | |
| 1000 | + | |
| 1001 | + | |
| 1002 | + | |
| 1003 | + | |
| 1004 | + | |
997 | 1005 | | |
998 | 1006 | | |
999 | 1007 | | |
| |||
1036 | 1044 | | |
1037 | 1045 | | |
1038 | 1046 | | |
| 1047 | + | |
| 1048 | + | |
| 1049 | + | |
1039 | 1050 | | |
1040 | 1051 | | |
1041 | 1052 | | |
| |||
0 commit comments