问题描述
从使用反射简单的介绍一下,它看起来像 String.Substring()
每个子分配内存。我是纠正这种情况?我想这不会是必要的,因为字符串是不可变的。
From a brief look using Reflector, it looks like String.Substring()
allocates memory for each substring. Am I correct that this is the case? I thought that wouldn't be necessary since strings are immutable.
我的根本目标是创建一个的IEnumerable<字符串>斯普利特(这个字符串,字符)
扩展方法,该方法不分配更多的内存。
My underlying goal was to create a IEnumerable<string> Split(this String, Char)
extension method that allocates no additional memory.
推荐答案
原因之一,大部分语言与不可改变的字符串创建新的子,而不是指到现有的字符串是因为这将与垃圾收集这些字符串后干扰。
One reason why most languages with immutable strings create new substrings rather than refer into existing strings is because this will interfere with garbage collecting those strings later.
如果一个字符串用于其子会发生什么,但随后的大串无法访问(除非通过子)。较大的字符串将是无法收回的,因为这会使无效的子字符串。什么似乎是一个很好的方式,以节省内存在短期内成为在长期内存泄漏。
What happens if a string is used for its substring, but then the larger string becomes unreachable (except through the substring). The larger string will be uncollectable, because that would invalidate the substring. What seemed like a good way to save memory in the short term becomes a memory leak in the long term.
这篇关于为什么.NET创建的,而不是指向到现有的字符串新的子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!