вторник, 14 февраля 2017 г.

Java StringBuilder and StringBuffer

As to know more about the implementation of the JVM I started to look at the java source code. StringBuilder and StringBuffer are two pretty often used classes.
Documentation says that it is recommended to use StringBuilder class as it will be faster under most implementations. But.. documentation does not say about possible performance gains.
I wrote a quick check for appending String and char for both classes.
For the tests I used Oracle JDK 1.8.0b51.  Here is the sample code:
    @Test
    public void stringBufferTest(){
        Eap.execute(()->{
            StringBuffer stringBuffer = new StringBuffer();
            String a = "a";
            for (int i = 0; i< $256_MEGABYTES; i++){
                stringBuffer.append(a);
            }
        });
    }
    @Test
    public void stringBuilderTest(){
        Eap.execute(()->{
            StringBuilder stringBuilder = new StringBuilder();
            String b = "b";
            for (int i = 0; i< $256_MEGABYTES; i++){
                stringBuilder.append(b);
            }

        });
    }

And results:
Time is: 9,105000 seconds
Time is: 3,220000 seconds

Absolute numbers tell nothing, so StringBuilder is almost 2.8 faster then StringBuffer. 

For chars I just substitute String a = "a" to char a = 'a' and String b = "b" to char b = 'b'.

In case of char appending we get following results:
Time is: 8,623000 seconds
Time is: 1,221000 seconds
So StringBuilder is almost 7 times faster then StringBuffer. 

Although these results were obtained on relatively long strings it is much more clear now which class to use in your application (depending on the requirements of course). Interesting fact is that both StringBuffer and StringBuilder extend from AbstractStringBuilder.

A couple of questions to the internal design of these classes:
1) both of them expose internal capacity, which is 16 by default. Why it is 16? What is this magic number for?
2) Overloaded constructors with different semantics. So, one constructor accepts capacity and another one accepts string.
3) Both classes provide methods capacity() and length(). Both of them return data. Why didn't they call them with get prefix like getCapacity() and getLength()?

Комментариев нет:

Отправить комментарий