1

I was wondering if there are some advantages of doing

sb.append('\n').toString();

over:

sb.append("\n").toString();

"\n" instead of '\n' in terms of performance.

Will the version with character instead of string will be more efficient in terms of memory or will compiler figure out that the string is actual a character?

9
  • 3
    Why don't you look at the source code of the two append methods to see what happens? Commented Jul 19, 2016 at 10:33
  • What version of JDK are you using? Commented Jul 19, 2016 at 10:33
  • He's asking about wether jvm or javac will optimize one char strings, not what StringBuilder does wether it receives strings or chars. Commented Jul 19, 2016 at 10:34
  • Why do you even bother? What's the problem behind that? Commented Jul 19, 2016 at 10:36
  • 2
    @PiotrekHryciuk in theory the only valid answer is that it depends (on your compiler, jdk version etc.). On openjdk v8, the char version is probably faster. You can always test it with jmh Commented Jul 19, 2016 at 10:38

3 Answers 3

1

I did a small experiment to test the performance of the two options:

It seems that '\n' is definitely faster on a large scale manipulation.

But hardly noticeable in a smaller scale. Even the memory consumption seems to be very trivial.

This code appends \n , 1000 times:

    package test;           
                
                
    public class StringAppend {         
                
        public static void main(String[] args) {            
                
            //Run 1         
            long startTime = System.nanoTime();         
            long startMem = Runtime.getRuntime().freeMemory();          
            StringBuilder sb1 = new StringBuilder("This is a test");            
            for (int i = 1; i <= 1000; i++) {           
                sb1.append("\n");           
            }           
            sb1.append("To Test \"\\n\"");          
        System.out.println("sb1 = " + sb1.toString());          
        long endTime = System.nanoTime();           
        long endMem = Runtime.getRuntime().freeMemory();            
            
        //Run 2         
        long startTime2 = System.nanoTime();            
        long startMem2 = Runtime.getRuntime().freeMemory();         
        StringBuilder sb2 = new StringBuilder("This is a test");            
        for (int i = 1; i <= 1000; i++) {           
            sb1.append('\n');           
        }           
        sb1.append("To Test '\\n'");            
        long endTime2 = System.nanoTime();          
        long endMem2 = Runtime.getRuntime().freeMemory();           
        System.out.println("Run1: append \"\\n\"execution time [" + (endTime - startTime) + " nanos], Memory " + "[" + (endMem - startMem) + "]");          
        System.out.println("Run2: append '\\n' execution time [" + (endTime2 - startTime2) + " nanos], Memory " + "[" + (endMem2 - startMem2) + "]");           
    }           
}           

Below is the result that I noticed on a high performance laptop:

Run1: append "\n"execution time [767526 nanos], Memory [0]

Run2: append '\n' execution time [121823 nanos], Memory [0]

Sign up to request clarification or add additional context in comments.

Comments

1

In class java.lang.AbstractStringBuilder, appending a single char will ensure/expand capacity by 1, while appending a CharSequence or String will do the same with the object's length.

Arguably there would be a slight overhead as length is invoked in the later cases.

You're hardly ever going to notice it though.

One may also argue that appending a String literal has the overhead of interning the literal, but again, that should be considered as minimal overhead.

Comments

0

Java does create an instance of a string even for a single character string.

java.lang.String:

public class Test{
    public static void main(final String[] args){
        System.out.println("c".getClass().getName());
    }
}

1 Comment

By "single character" he means '\n'. Note the ' instead of ". Characters bounded by ' are of the primitive type char.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.