cool hit counter Do-it-yourself implementation of StringBuffer class in Java_Intefrankly

Do-it-yourself implementation of StringBuffer class in Java


Reviewing the basics of Java online, I saw String and StringBuffer here, and simply implemented the StringBuffer class, and did performance tests on String, StringBuffer, and MyStringBuffer (my own implementation of StringBuffer class name) for splicing strings.

Both String and StringBuffer are implemented internally by character arrays, but the String internal character array is fixed in length at the first assignment and cannot be changed, while the StringBuffer internal character array is left with a redundant length, and if the initial capacity is exceeded, the array is dynamically increased to make it look like a variable-length array.

StringBuffer is highly recommended over String when doing a lot of string stitching, because String stitching requires creating a String object to hold the string to be stitched each time you stitch a string. StringBuffer splices strings by expanding the space of the character array on top of the original string object and does not create a new StringBuffer object, which is the reason why StringBuffer is faster than String.

Here's a simple implementation of StringBuffer, named MyStringBuffer.

public class MyStringBuffer{
    private int capacity = 16; // Initial Capacity
    private int length = 0; //  Length of literal value string
    private char[] value;
    
    public MyStringBuffer() {
        value = new char[capacity];
    }
    
    public MyStringBuffer(String str) {
        if(str == null) {
            return;
        }
        length = str.length();
        // str The length of the string is greater than the initial capacity
        if(capacity < length) {
            capacity += length;
            value = new char[capacity];
            System.arraycopy(str.toCharArray(), 0, value, 0, length);
        } else {
            value = new char[capacity];
            System.arraycopy(str.toCharArray(), 0, value, 0, length);
        }
    }
    
    public void append(String str) {
        insert(length, str);
    }

    public void append(char c) {
        insert(length, String.valueOf(c));
    }

    public void insert(int pos, String str) {
        if(pos < 0 || pos > length || str == null) {
            return;
        }
        //  Not enough capacity
        while((length + str.length()) > capacity) {
            capacity += length + str.length();
            char[] newValue = new char[capacity];
            System.arraycopy(value, 0, newValue, 0, length);
            value = newValue;
        }
        char[] temp = str.toCharArray();
        //  move first and insert later
        System.arraycopy(value, pos, value, pos + temp.length, length - pos);
        System.arraycopy(temp, 0, value, pos, temp.length);
        length += temp.length;
    }

    public void insert(int pos, char c) {
        insert(pos, String.valueOf(c));
    }

    public void delete(int start) {
        delete(start, length - 1);
    }

    public void delete(int start, int end) {
        if(start < 0 || start > length || end < 0 || end > (length - 1) || start > length) {
            return;
        }
        System.arraycopy(value, end, value, start, length - end);
        length -= (end - start);
    }

    public void reverse() {
        //  Method I  indirect method
        /*char[] temp = new char[value.length];
        for(int i = 0, j = length; i < length; i++, j--) {
            temp[i] = value[j - 1];
        }
        value = temp;*/
        //  Method II  direct method
        for(int i = 0; i < length / 2; i++) {
            char temp = value[i];
            value[i] = value[length - i - 1];
            value[length - i - 1] = temp;
        }
    }

    public int length() {
        return length;
    }
    
    public String toString() {
        char[] realValue = new char[length];
        System.arraycopy(value, 0, realValue, 0, length);
        return new String(realValue);
    }

    public int capacity() {
        return capacity;
    }
}

The following is the test class MyStringBufferTest for MyStringBuffer.

package com.wenshixin.character;

import org.junit.Test;

public class MyStringBufferTest {
    final int TIMES = 1000000; //  Number of cycles
    final double DIVISOR = 1000000.0; //  divisor (math.)
    
    @Test
    public void constructorTest() {
        MyStringBuffer myStringBuffer = new MyStringBuffer("Weizhiwen");
        System.out.println(myStringBuffer);
        MyStringBuffer longStringBuffer = new MyStringBuffer("It's a long road, the only key.");
        System.out.println(longStringBuffer);
    }
    
    @Test
    public void lengthAndCapacityTest() {
        MyStringBuffer myStringBuffer = new MyStringBuffer("Weizhiwen");
        System.out.println("length:"+myStringBuffer.length());
        System.out.println("capacity:"+myStringBuffer.capacity());
        MyStringBuffer longStringBuffer = new MyStringBuffer("It's a long road, the only key.");
        System.out.println("length:" + longStringBuffer.length());
        System.out.println("capacity:" + longStringBuffer.capacity());
    }
    
    @Test
    public void reverseTest() {
        MyStringBuffer myStringBuffer = new MyStringBuffer("Weizhiwen");
        myStringBuffer.reverse();
        System.out.println(myStringBuffer);
    }
    
    @Test
    public void insertTest() {
        MyStringBuffer myStringBuffer = new MyStringBuffer("Weiwen");
        myStringBuffer.insert(3, "zhi");
        System.out.println(myStringBuffer);
        myStringBuffer.insert(0, "I'm ");
        System.out.println(myStringBuffer);
        myStringBuffer.insert(myStringBuffer.length(), "!");
        System.out.println(myStringBuffer);
        myStringBuffer.insert(myStringBuffer.length(), "
It's a long road, the only key.");
        System.out.println(myStringBuffer);
        myStringBuffer.insert(-1, "nothing");
        System.out.println(" Insert value below lower limit position, shows:" + myStringBuffer);
        myStringBuffer.insert(myStringBuffer.length() + 2, "nothing");
        System.out.println(" Insert value above the upper position, shows:" + myStringBuffer);
    }
    
    @Test
    public void appendTest() {
        MyStringBuffer myStringBuffer = new MyStringBuffer();
        myStringBuffer.append("I'm Weizhiwen");
        System.out.println(myStringBuffer);
        myStringBuffer.append("!");
        System.out.println(myStringBuffer);
    }
    
    @Test
    public void deleteTest() {
        MyStringBuffer myStringBuffer = new MyStringBuffer("I'm not Weizhiwen!");
        myStringBuffer.delete(3, 7);
        System.out.println(myStringBuffer);
    }
    
    @Test
    public void stringPerformenceTest() {
        String string = "1";
        Long startTime = System.currentTimeMillis();
        System.out.println(startTime);
        for(int i = 0; i < TIMES; i++) {
            string += "0";
        }
        Long endTime = System.currentTimeMillis();
        System.out.println(endTime);
        double avgTime = (endTime - startTime) / DIVISOR; 
        System.out.println("String The average time for a splice is:" + avgTime + " millisecond, ms。");
    }
    
    @Test
    public void stringBufferPerformenceTest() {
        StringBuffer stringBuffer = new StringBuffer("1");
        Long startTime = System.currentTimeMillis();
        System.out.println(startTime);
        for(int i = 0; i < TIMES; i++) {
            stringBuffer.append("0");
        }
        Long endTime = System.currentTimeMillis();
        System.out.println(endTime);
        double avgTime = (endTime - startTime) / DIVISOR; 
        System.out.println("StringBuffer The average time for a splice is:" + avgTime + " millisecond, ms。");
    }
    
    @Test
    public void myStringBufferPerformence() {
        MyStringBuffer myStringBuffer = new MyStringBuffer("1");
        Long startTime = System.currentTimeMillis();
        System.out.println(startTime);
        for(int i = 0; i < TIMES; i++) {
            myStringBuffer.append("0");
        }
        Long endTime = System.currentTimeMillis();
        System.out.println(endTime);
        double avgTime = (endTime - startTime) / DIVISOR; 
        System.out.println("MyStringBuffer The average time for a splice is:" + avgTime + " millisecond, ms。");
    }
}

I made separate loops 1000 sub-,10,000 sub-,100,000 sub-,1000,000 subpooling, The result is that the average splicing time t(StringBuffer) < t(MyStringBuffer) < t(String)。

By implementing StringBuffer by myself, I deepened my understanding of StringBuffer and Stringers, but I still need to strengthen my Java foundation.

Personal GitHub address.https://github.com/weizhiwen We welcome visits.


Recommended>>
1、New hippo mutual entertainment five outside hang cheat aids new hippo mutual entertainment five outside hang cheat software assistant
2、A beautyloving ladys nightmare Adobe makes it easier to judge photoshopped images via AI
3、Blockchain 100 Questions
4、Python Fundamentals 5 Common Operations on Text Sequences
5、Shanghai Cloud Shield Invited to DEFCON to Collaborate on Building an International Platform for Cyber Security Exchange

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号