• Is the immutability of Strings taken into account in the Java implementation of

    Home » Forums » Developers, developers, developers » Web design and development » Is the immutability of Strings taken into account in the Java implementation of

    Tags:

    Author
    Topic
    #2525180

    Because Strings in Java are immutable, I’ve always concatenated them using StringBuilder or StringBuffer. Is the String.format() function as capable as StringBuilder or StringBuffer in this regard? To put it another way, does String.format() handle memory in the same way as StringBuffer or StringBuilder do?

    Viewing 0 reply threads
    Author
    Replies
    • #2525362

      In the sense that it is will produce the same output, String.format() is as capable as StringBuilder/StringBuffer, but StringBuilder/StringBuffer are much more efficient than String.format(), probably because String.format() is having to parse your string.

      So, if you have to choose just between the two then I would say that the general rule I would use is to use StringBuilder/StringBuffer where performance is more important, and String.format() where neatness of code is more important.

      However, I think the better solution would be to use the string concatenation operator (IE. string1 + string2), which is literally just shorthand for StringBuilder/StringBuffer (and is thus just as fast), and, in my personal opinion, looks just as neat as String.format().

      1 user thanked author for this post.
    Viewing 0 reply threads
    Reply To: Is the immutability of Strings taken into account in the Java implementation of

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: