Why can .NET not have memory leaks?

前端 未结 16 1441
春和景丽
春和景丽 2020-12-07 16:17

Ignoring unsafe code, .NET cannot have memory leaks. I\'ve read this endlessly from many experts and I believe it. However, I do not understand why this is so.

It is

16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 17:04

    The best example I've found was actually from Java, but the same principle applies to C#.

    We were reading in text files that consisted of many long lines (each line was a few MB in heap). From each file, we searched for a few key substrings and kept just the substrings. After processing a few hundred text files, we ran out of memory.

    It turned out that string.substring(...) would keep a reference to the original long string... even though we kept only 1000 characters or so, those sub-strings would still use several MB of memory each. In effect, we kept the contents of every file in memory.

    This is an example of a dangling reference that resulted in leaked memory. The substring method was trying to reuse objects, but ended up wasting memory.

    Edit: Not sure if this specific problem plagues .NET. The idea was to illustrate an actual design/optimization performed in a garbage collected language that was, in most cases, smart and useful, but can result in a unwanted memory usage.

提交回复
热议问题