Java String 是不可变的,所以
当您创建一个字符串时,会在堆中为其分配一块内存,当您更改其值时,会为该字符串创建一个新的内存块,并且旧的内存块有资格进行垃圾回收,例如
String str = func1_return_big_string_1()"; //not literal
String str= func2_return_big_string_2()"; //not literal
但是由于垃圾收集需要时间来启动,所以我们实际上在堆中拥有包含大字符串 1 和 2 的内存。如果这种情况经常发生,它们对我来说可能是个问题。
有没有办法让大字符串 2 在内存中使用字符串 1 的相同位置,所以当我们将大字符串 2 分配给 str 时,我们不需要额外的空间。
编辑:感谢所有输入,最后我意识到我不应该期望 java 代码表现得像 c++ 代码(即不同的内存占用)。我编写了一个 c++ 11 演示,它按预期工作,最大的内存占用约为 20M(我试图加载的最大文件),右值引用和移动赋值运算符都按预期启动。下面的演示在 VS2012 中使用 c++ 11 完成。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <thread>
using namespace std;
string readFile(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(&bytes[0], fileSize);
return string(&bytes[0], fileSize);
}
class test{
public:
string m_content;
};
int _tmain(int argc, _TCHAR* argv[])
{
string base("c:\\data");
string ext(".bin");
string filename;
test t;
//std::this_thread::sleep_for(std::chrono::milliseconds(5000));
cout << "about to start" << endl;
for(int i=0; i<=50; ++i) {
cout << i << endl;
filename = base + std::to_string(i) + ext;
//rvalue reference & move assignment operator here
//so no unnecessary copy at all
t.m_content = readFile(filename);
cout << "szie of content" << t.m_content.length() << endl;
}
cout << "end" << endl;
system("pause");
return 0;
}