我在我的代码中使用了几个字符串,这些字符串将在循环中重用,我想知道什么是初始化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)
循环之后,不再使用字符串.