The Java string is immutable, therefore
when you create a string, a memory block is assigned to it on the heap, and when you change its value, a new memory block is created for this string, and the old one has the right to garbage collection for example
String str = func1_return_big_string_1()"; //not literal String str= func2_return_big_string_2()";
But since garbage collection takes time to strike, so we almost have memory on the heap containing both large lines 1 and 2. They can be a problem for me if this happens a lot.
Is there a way to make large line 2 to use the same memory in line 1, so we donβt need to have extra space when we assign large line 2 to str.
Edit: Thanks for all the input, and in the end, I realized that I should not expect Java code to behave like C ++ code (i.e. a different amount of memory). I wrote a C ++ 11 demo that works as expected, the largest memory capacity is around 20 M (the largest file I tried to download) using the rvalue link and the redirect destination operator, as expected. The following demo is done in VS2012 with 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; }
java string memory
Gobst
source share