内存使用大比拼 之 String – StringBuffer

String与StringBuffer,种种资料表明大字符拼接时StringBuffer忧郁String如:

StringMemory.java文件:

public class StringMemory
{
    public static void main(String[] args)
    {
         String tempStr="byd is our home.";
         //String tempStr="we love byd,byd is our home.";
 
         System.out.println("虚拟机可用内存:"+Runtime.getRuntime().maxMemory()/1024/1024+" M");
         System.out.println("循环前已用内存:"+Runtime.getRuntime().totalMemory()/1024/1024+" M");
 
         int count=0;
         while(true){
 
             try{
                 tempStr+=tempStr;
                 count++;
             }catch(Error o){
                 System.out.println("内存溢出,共循环 "+count+" 次");
                 System.out.println("tempStr 实际的字节数:"+tempStr.length()/1024/1024+" M");
                 System.out.println("循环后已用内存:"+Runtime.getRuntime().totalMemory()/1024/1024+" M");
                 break;
             }
         }
 
     }
 }

StringBufferMemory.java文件:

public class StringBufferMemory
{
     public static void main(String[] args)
     {
         StringBuffer tempStrB=new StringBuffer("byd is our home.");
         //StringBuffer tempStrB=new StringBuffer("we love byd,byd is our home.");
 
         System.out.println("虚拟机可用内存:"+Runtime.getRuntime().maxMemory()/1024/1024+" M");
         System.out.println("循环前已用内存:"+Runtime.getRuntime().totalMemory()/1024/1024+" M");
 
         int count=0;
         while(true){
 
             try{
                 tempStrB.append(tempStrB);
                 count++;
             }catch(Error o){
                 System.out.println(o+",共循环 "+count+" 次");
                 System.out.println("tempStrB 实际的字节数:"+tempStrB.length()/1024/1024+" M");
                 System.out.println("循环后已用内存:"+Runtime.getRuntime().totalMemory()/1024/1024+" M");
                 break;
             }
         }
 
     }
 }

运行如下:

可用看出实际字节为8M的Sting字符串占内存为63M,而实际字节为16M的StringBuffer才占内存为63M,所以大字符串还是StringBuffer比较好。

疑问:

如上在StringMemory.java和StringBufferMemory.java文件中,把字符串初始为”we love byd,byd is our home.“,如注释。却看不出StringBuffer在内存使用上的优越。执行结果如下:

即使增大虚拟机内存也是同样:

为何?没想清楚,哪哥们帮忙解答下。

附:

  • 用HashMap提高内存查询速度
  • 用arrayCopy()提高数组截取速度
出处:http://www.zhaiqianfeng.com    
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/zhaiqianfeng/p/4617861.html