我在我的代码中使用了几个字符串,这些字符串将在循环中重用,我想知道什么是初始化String变量以提高内存使用量的最佳方法:
// Just for sample purposes I will declare a Map, but the same thing
// applies for an ArrayList, Database Set, etc. You get the point.
Map<String, String> sampleMap = getMap();
int mapSize = sampleMap.size();
// String initialization
String a;
String b = new String();
String c = "";
for(int i = 0; i < mapSize; i++){
a = sampleMap.get(i);
b = someFunc(a);
c = anotherFunc(a);
// Do stuff with all the Strings
}
Run Code Online (Sandbox Code Playgroud)
循环之后,不再使用字符串.
减少变量的范围以将它们限制在使用它们的位置:
// Just for sample purposes I will declare a Map, but the same thing
// applies for an ArrayList, Database Set, etc. You get the point.
Map<String, String> sampleMap = getMap();
int mapSize = sampleMap.size();
for(int i = 0; i < mapSize; i++){
String a = aFunc();
String b = sampleMap.get(i);
String c = anotherFunc();
// Do stuff with the Strings
}
Run Code Online (Sandbox Code Playgroud)
声明循环外的变量没有性能优势.
您无法优化代码段中字符串的初始化或内存使用情况,原因如下:
Java字符串是不可变的 - 您不能更改字符串中的字符,但可以指向新字符串.
在循环中,被调用的函数(例如aFunc()or get())是负责分配字符串而不是循环的函数.
对于高级程序员:如果您确实想要优化字符串的内存使用,则需要使用StringBuffer/StringBuilder或原始字符数组,并将它们传递给各种函数调用.您将在循环之前创建缓冲区,并将其传递给get()其他函数,以便它们使用这一个缓冲区而不是分配和返回它们自己的缓冲区.