Middle+
Miks on .NET-is vajalik suurte objektide virna (Large Object Heap) ja väikeste objektide virna (Small Object Heap) eraldamine?
sobes.tech AI
Vastus AI-lt
LOH and SOH separation optimizes memory management for objects of different sizes.
Small Object Heap (SOH)
- Stores objects up to 85 KB.
- Uses a generational garbage collector (Generational Garbage Collection - GC).
- Newly created objects are in generation 0. Surviving objects are promoted to generation 1, then to generation 2.
- Garbage collection is more frequent and efficient for small objects.
// Example of creating an object on SOH
string smallString = "This is a small string"; // Less than 85 KB
object smallObject = new object(); // Small object
Large Object Heap (LOH)
- Stores objects of size 85 KB and above.
- Not generational like SOH. Usually cleaned only during full garbage collection (generation 2).
- Memory allocation on LOH can be slower due to searching for a contiguous block of memory.
- Fragmentation of LOH can cause issues with allocating large objects, even if total free memory is sufficient.
- Objects on LOH are not moved by GC by default (with .NET Framework 4.5.1, it is possible to compress LOH, but this is disabled by default and has its costs). This prevents expensive copying of large data volumes.
// Example of creating an object on LOH
byte[] largeArray = new byte[100 * 1024]; // Size 100 KB > 85 KB
Advantages of separation
- Garbage collection optimization: Generational GC is much more efficient for small, short-lived objects on SOH. Moving objects to SOH is relatively fast.
- Reducing SOH fragmentation: Moving large objects would be extremely costly and lead to severe fragmentation. Placing them on a separate LOH solves this problem.
- Minimizing costs: Moving large objects to LOH would incur significant costs. Default GC does not move them, avoiding these costs.
- Improving memory allocation performance: Allocation on SOH is often very fast (using a pointer), while on LOH it may require searching for a suitable free block. Separation allows maintaining high allocation speed for most (small) objects.
| Characteristic | Small Object Heap (SOH) | Large Object Heap (LOH) |
|---|---|---|
| Object size | Up to 85 KB | 85 KB and above |
| GC model | Generational (0, 1, 2) | Non-generational (default) |
| Object movement | Yes (compaction) | No (default) |
| Cleanup frequency | More often | Less often (usually with generation 2) |
| Fragmentation risk | Low (compacts) | High |