阅读964 返回首页    go 阿里云 go 技术社区[云栖]


String、StringBuffer、StringBuilder的区别

String、StringBuffer、StringBuilder的区别

理论(这几个东西的区别是啥?)---先不说话我们先上代码,不管懂不懂,先照抄!

package com.sandy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Iterator;

/**
 * Created by alittlefish on 2017/8/17.
 */
public class StringCompare {
    public static void main(String[] arg) {
        try {
            Integer count = 7000;
            String content = "[\n" +
                    "{\n" +
                    "\"moduleId\":3,\n" +
                    "\"moduleName\":\"测试板块\",\n" +
                    "\"moduleTitle\":\"测试板块\",\n" +
                    "\"moduleData\":{\n" +
                    "\"startDate\":\"2017-06-26\",\n" +
                    "\"endDate\":\"2017-06-26\"\n" +
                    "},\n" +
                    "\"moduleHtml\":\"DateRange\",\n" +
                    "\"moduleType\":1,\n" +
                    "\"moduleSort\":0,\n" +
                    "\"moduleObsolete\":0,\n" +
                    "\"moduleImage\":\"https://sandy.com/%E5%B7%A5%E6%9C%9F.png%2Forigine%2F37c6bb95-efee-4f7c-9b07-2df0051c5137?imageMogr2/auto-orient/strip/quality/90\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"moduleId\":188,\n" +
                    "\"moduleName\":\"测试板块描述\",\n" +
                    "\"moduleTitle\":\"测试板块描述\",\n" +
                    "\"moduleData\":{\n" +
                    "\"moduleDesc\":\"StringBuilder板块\",\n" +
                    "\"content\":\"aontent\",\n" +
                    "\"files\":[\n" +
                    "]\n" +
                    "},\n" +
                    "\"moduleHtml\":\"ConsultContent\",\n" +
                    "\"moduleType\":1,\n" +
                    "\"moduleSort\":0,\n" +
                    "\"moduleObsolete\":0,\n" +
                    "\"moduleImage\":\"https://sandy.com/%E9%A1%B9%E7%9B%AE%E6%8F%8F%E8%BF%B0.png%2Forigine%2F9a079c77-3eca-44d2-905b-90e95cb6bd2b?imageMogr2/auto-orient/strip/quality/90\"\n" +
                    "}]";
            content = "{result:" + content + "}";
            JSONObject object = JSONObject.parseObject(content);
            JSONArray array = object.getJSONArray("result");
            Iterator<Object> iterator = array.iterator();
            StringBuffer result = new StringBuffer();
            StringBuilder result1 = new StringBuilder();
            String result2 = new String("aontent");
            while (iterator.hasNext()) {
                JSONObject ob = (JSONObject) iterator.next();
                if (ob.getString("moduleName").equals("测试板块描述")) {
                    JSONObject re = ob.getJSONObject("moduleData");
                    result = result.append(re.getString("content"));
                    result1 = result1.append(re.getString("content"));
                }
            }

            result.replace(0, 1, "c");    //把位置0到0(也就是a)换成c
            Long pre = System.currentTimeMillis();
            String addTest = ":test";
            for (int i = 0; i < count; i++) {
                result.append(addTest);     //添加7000次比较添加时间
            }
            Long now = System.currentTimeMillis();
            result.append(addTest);     //添加字符串"test"

            result1.replace(0, 1, "c");    //把位置0到0(也就是a)换成c
            Long pre1 = System.currentTimeMillis();
            String addTest1 = ":test";
            for (int i = 0; i < count; i++) {
                result1.append(addTest1);   //添加字符串"test1"
            }
            Long now1 = System.currentTimeMillis();

            result2.replace('a', 'c');   //将里面的a全部替换成c
            Long pre2 = System.currentTimeMillis();
            String addTest2 = ":test";
            for (int i = 0; i < count; i++) {
                result2 = result2 + addTest2;
            }
            Long now2 = System.currentTimeMillis();

            System.out.println("StringBuffer拼接字符串时间:" + String.valueOf(now - pre) + "-----result:" + result2);
            System.out.println("StringBuilder拼接字符串时间:" + String.valueOf(now1 - pre1) + "-----result1:"+result1);
            System.out.println("String拼接字符串时间:" + String.valueOf(now2 - pre2) + "-----result2:"+result2);
//            System.out.println(StringCompare.modify("abc"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String modify(String greeep) {
        String update = greeep.substring(1, 3);
        return update + "p!";

    }
}

结果:_String

好了上面对着上面的运行结果,我们来聊5毛钱的区别

区别

  1. String:Strings are constant(字符串常量、线程安全);
  2. StringBuffer:A thread-safe, mutable sequence of characters(字符串变量、线程安全);
  3. StringBuilder:A mutable sequence of characters(字符串变量、线程不安全)。 ####划重点,由上面的运行时间和最后的字符串result,可以看出:
  4. 运行时间: StringBuilder<StringBuffer<String;
  5. ACID原则 :StringBuffer、String的内容没变,SttingBuilder改变

因此如果是单线程处理较短的字符串建议使用字符构建器:StringBuilder,多线程使用StringBuffer,StringBuilder、StringBuffer就是为构建字符串而生,其余建议String

源代码

看源代码,反正我是把这三个类看了滴。
String的优点是:编译器可以让字符串字符共享。
java字符串中的字符是不可以修改的,例如:result = "acontent"字符串"acontent"永远包含a、c、o、n、t、e、n、t代码单元。但是字符变量result是阔以修的。
你可以想象各种字符串存放在公共的存储池中(如果看过编译原理应该很好理解,写C的大佬们总把字符串理解为字符类型的数组),字符串变量指向存储池中相应的位置。如果复制一个字符串变量,原始的字符串将和复制的共享字符串。

常用方法、使用

JDK5.0中引入了StringBuilder,前身是StringBuffer,所以我们对比String和StringBuffer的方法。

相同

  • 这两个类都是用来处理字符串的的,都提供了length()、toString()、charAt()、subString()方法,并且在两个类中用法相同。
  • 字符在字符串中的索引位置都是从0开始。

不同

  • String类的subString()、concat()、toLowerCase()、toUpperCase()、trim()等方法都不会改变字符串本身,而是创建一个新的包含改变后的新的字符串对象;StringBuffer类的append()、replaceAll()、replaceFirst()、insert()、setCharAt()等方法都会改变字符缓冲区中字符串内容。
  • String类涵盖Object类的equals()方法,StringBuffer类不包含。
  • String类字符串拼接阔以直接用"+"StringBuffer类say no!
  • 两个类都覆盖了Object的toString()方法但是实现却不同,String类中的返回当前Strings实例本身的引用,StringBuffer类返回以当前缓冲区的所有字符为内容的新String对象的引用

最后更新:2017-09-26 09:32:47

  上一篇:go  Spring Boot and OAuth2
  下一篇:go  FG