Java 使用字符串使用最大内存
是否有任何方法可以使用Java 使用字符串使用最大内存,java,string,garbage-collection,Java,String,Garbage Collection,是否有任何方法可以使用字符串来利用系统的最大内存? 我正在使用运行时显示可用内存。我已尝试使用以下代码: class Mem{ public static void main(String[] args) { System.out.println(Runtime.getRuntime().maxMemory()); System.out.println(Runtime.getRuntime().totalMemory());
字符串来利用系统的最大内存?
我正在使用运行时
显示可用内存。我已尝试使用以下代码:
class Mem{
public static void main(String[] args) {
System.out.println(Runtime.getRuntime().maxMemory());
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
String str=new String("Hi");
for(long i=0;i<1000000;i++){
str+="aa";
//System.out.println(i);
}
System.out.println(Runtime.getRuntime().freeMemory());
}
}
class Mem{
公共静态void main(字符串[]args){
System.out.println(Runtime.getRuntime().maxMemory());
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freemory());
String str=新字符串(“Hi”);
for(long i=0;istr+=“aa”
每次创建一个新字符串,并重新分配str
,以便旧字符串可以进行垃圾收集
但是,如果您进行足够的迭代,它将在某个阶段耗尽内存
您应该将for循环放在try/catch块中,catch OutOfMemoryError并将print语句包含在catch块中。str+=“aa”
每次创建一个新字符串并重新分配str
,以便旧字符串可以进行垃圾收集
但是,如果您进行足够的迭代,它将在某个阶段耗尽内存
您应该将for循环放在try/catch块、catch-OutOfMemoryError中,并在catch块中包含print语句。最后,字符串仅包含200万个字符。如果要使代码内存不足,请更改
str += "aa";
到
这将使字符串呈指数级增长,即使迭代次数不多,垃圾收集也无济于事。最后,字符串仅包含200万个字符。如果要使代码内存不足,请更改
str += "aa";
到
这将使字符串呈指数级增长,即使迭代次数不多,垃圾收集也无济于事
System.out.println(Runtime.getRuntime().maxMemory());
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
String str = new String(new char[32_000_000]);
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
请注意,str+=“aa”
速度太慢,您可能会得出错误的结论。GC无法释放您案例中的任何内存
System.out.println(Runtime.getRuntime().maxMemory());
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
String str = new String(new char[32_000_000]);
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
请注意,str+=“aa”
非常慢,您可能会得出错误的结论。在您的情况下,GC无法释放任何内存
List<byte[]> bytes = new ArrayList<>();
for(int i = 0; i < 1000; i++)
bytes.add(new byte[10000000]); // 10 MB
List bytes=new ArrayList();
对于(int i=0;i<1000;i++)
字节。添加(新字节[10000000]);//10 MB
快速分配和保存大量内存的方法是
List<byte[]> bytes = new ArrayList<>();
for(int i = 0; i < 1000; i++)
bytes.add(new byte[10000000]); // 10 MB
List bytes=new ArrayList();
对于(int i=0;i<1000;i++)
字节。添加(新字节[10000000]);//10 MB
那应该会更快!是的,当然!!str+=str
做到了。为什么我没有想到呢?但是它比我想象的慢多了。我按照assylias的建议加入了try/catch块,并捕获了OutOfMemoryException
即使迭代次数只有50次!!那应该会更快!是的,当然!!str+=str
做到了。为什么我没有想到呢?但它比我想象的慢多了。我按照assylias的建议加入了try/catch块,并捕获了OutOfMemoryException
,即使迭代次数只有50次!!呵呵,这是一种以碎片方式浪费资源的好方法,+1来自我。你可以从OfMemory中捕获第一个并减少大小从几何角度来说,数组的e可以划掉最后一位…这些数组将直接进入永久空间。也就是说,应该不会有太多的碎片。我明白了,那么链表是更好的选择吗?呵呵,以碎片的方式浪费资源的好方法,+1来自我。你可以抓住内存的第一位,并减少ar的大小以几何方式进行射线扫描以刮除最后一位…这些阵列将直接进入永久空间。也就是说,应该不会有太多碎片。我明白了,那么链表是更好的选择吗?