java-字符串

来源:互联网 发布:淘宝怎么防举报防排查 编辑:程序博客网 时间:2024/06/05 22:45

字符串在开发中非常常见,了解String是非常有必要的,还能提升系统性能。

(一)不可变性

String一旦创建无法修改,不可变性在多线程中不需要锁和同步,能提升系统性能。

String s = "123" + "456" + "789";
相当于先生成123456对象,再拼接生成123456789。但编译过程中,编译器自己优化,用反编译查看,该句已转换为

String s = "123456789";

(二)存放位置

String常量存放于内存中的常量池,使用享元模式复用相同的字符串,减少内存占用。

String s1 = "123";String s2 = "123";System.out.println(s1==s2);//true


(三)StringBuilder和StringBuffer

String是不可变的,如果字符串常拼接需要使用StringBuilder或StringBuffer,尽管编译器经常会优化,但是并不经常高效。

StringBuffer是线程安全的,StringBuilder线程不安全,但是效率更高。

/** * String测试 *  * @author peter_wang * @create-time 2014-9-15 下午2:52:02 */public class StringThreadDemo    implements Runnable {    private StringBuilder sBuilder = new StringBuilder();    private StringBuffer sBuffer = new StringBuffer();    /**     * @param args     * @throws InterruptedException     */    public static void main(String[] args)        throws InterruptedException {        StringThreadDemo demo = new StringThreadDemo();        for (int i = 0; i < 10000; i++) {            Thread thread = new Thread(demo);            thread.start();        }        // 主线程休息3秒钟等子线程执行完        Thread.sleep(3000);        System.out.println("StringBuilder length:" + demo.sBuilder.length() + ",StringBuffer length:" +            demo.sBuffer.length());    }    @Override    public void run() {        sBuilder.append("1");        sBuffer.append("1");    }}
运行结果如下:

StringBuilder length:9974,StringBuffer length:10000
查看源码发现StringBuilder和StringBuffer都继承AbstractStringBuilder,调用父类append,但是StringBuffer有synchronized。

public AbstractStringBuilder append(String str) {        if (str == null)            str = "null";        int len = str.length();        if (len == 0)            return this;        int newCount = count + len;        if (newCount > value.length)            expandCapacity(newCount);        str.getChars(0, len, value, count);        count = newCount;//count线程不安全,可能导致计算错误String长度不对        return this;    }






0 0