我需要从数据库 (nvarchar) 中提取大型 Unicode 文本字符串(例如 200Mb)并存储在内存中进行处理。即我需要随机访问字符串的所有部分。
从严格以内存为中心的角度来看,使用 System.IO.MemoryStream 与 System.String 作为我的内存表示的优缺点是什么。
我正在尝试研究的一些因素是:
(如果流是 UTF8,我们是否几乎
减半)
我正在寻找关于这些点的清晰和建议,以及我没有想到的任何其他内存考虑?
注意:处理这些字符串可能有更好的方法,但此时我只是询问存储此类对象的内存考虑。
最佳答案
Looking at this from strictly memory centric point of view, what are the pro’s and con’s of using a System.IO.MemoryStream versus a System.String as my in memory representation.
Some factors I am trying to research are:
- How these objects act in a [hypothetical] highly fragmented low memory environment
IMO,MemoryStream 仅在编码很简单(例如 ASCII、ISO-8859-X 等)时才有用。如果编码是 UTF-8 和 如果您有非 ASCII 字符,那么处理将变得更加困难。当然,MemoryStream 几乎肯定会消耗更少的内存,但除此之外没有太大区别。在底层,MemoryStream 使用字节数组,它也需要分配在连续的内存块中。
- Actual size in memory (if stream is UTF8, have we nearly halved size)
对,对于纯 ASCII 字符,MemoryStream 将消耗等效字符串消耗的一半。
- Is there another object I have not thought about?
List<byte> // has a nicer interface for processing
字符串如何存储在数据库中? varchar 还是 nvarchar?
问候,
安德烈亚斯
关于.NET 字符串与流 - 内存配置文件和特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/397253/