concat与+的区别

要看看他们之间的区别,我们可以从源码分析两者的区别, 
concat是String方法,String重载了“+”操作符(提醒下:Java不支持其他操作符的重载)。 
concat源码: 

Java代码   收藏代码
  1.   public String concat(String str) {      
  2. int otherLen = str.length();      
  3. if (otherLen == 0) {          
  4. return this;  
  5.     }  
  6.     char buf[] = new char[count + otherLen];  
  7.     getChars(0, count, buf, 0);  
  8.     str.getChars(0, otherLen, buf, count);  
  9.     return new String(0, count + otherLen, buf);  
  10.     }  
源码中对String中+操作符的描述如下 
引用
The Java language provides special support for the string concatenation operator ( + ), and for conversion of  other objects to strings. String concatenation is implemented  through the StringBuilder(or  StringBuffer) class and its  append method.

简单的概括下:String本身是不变的对象,但是string的+号操作符是通过StringBuilder或StringBuffer(可以通过反汇编class文件,看到使用的StringBuilder来实现的。) 
========================= 
以上两个方法中都有开辟(new)以及销毁堆空间的操作,打大量的string操作导致效率很低。 

所以在大量操作string字符串时,StringBuilder的append方法是最好的选择!

引用自Anddy 的回复,原文地址:http://www.iteye.com/problems/41712

转载于:https://my.oschina.net/JiangTun/blog/268918

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值