我正在读取一个文件(这个文件包含一个2gb长的字符串)。
这是我的函数,它将文件的所有内容读入内存,然后拆分字符串并放置:
*reader = StreamReaderpublic List<char[]> GetAllContentAsList()
{
int bytesToRead = 1000000;
char[] buffer = new char[bytesToRead];
List<char[]> results = new List<char[]>();
while (_reader.Read(buffer, 0, bytesToRead) != 0)
{
char[] temp = new char[bytesToRead];
Array.Copy(buffer,temp,bytesToRead);
results.Add(temp);
}
return results;
}
当所有数据放入列表中时,它占用了4GB的RAM。当文件大小只有2GB时,这怎么可能呢?
*编辑
这就是我最终所做的。我没有将字节数组转换为字符串,而是直接传递字节并对其进行操作。这样,内存中仅使用2GB,而不是4GB。
public List<byte[]> GetAllContentAsList()
{
int bytesToRead = 1000000;
var buffer = new byte[bytesToRead];
List<byte[]> results = new List<byte[]>();
while (_reader.Read(buffer, 0, bytesToRead) != 0)
{
//string temp = Encoding.UTF8.GetString(buffer);
byte[] b = new byte[bytesToRead];
Array.Copy(buffer,b,bytesToRead);
results.Add(b);
}
return results;
}
Array.Copy(buffer,temp,bytesToRead);
会一直占用内存,直到垃圾回收器决定在你之后清理它吗? - Security Hound