• BRiaN (unregistered) in reply to Leaf
    Leaf:
    The BIG WTF for me is that in C# and Java the StringBuilder class doesn't override the + operator to make using the .Append method optional/obsolete. (because in my opinion .Append() makes code harder to read.

    Uhhh... the WTF here is that someone would refer to Java overloading (not overriding, they're different) an operator. Java, by design, doesn't overload operators. It makes code easier to read until you read:

    quiteAnAffair = yourMom + myDad

    and then realize much too late that the '+' operator is overloaded to act on Parent types as a party coordinating operation, and you should have bought wrapping paper and streamers rather than calling the private investigator.

  • jrockway (unregistered) in reply to MadPad

    The real WTF is why they didn't use a templating system for something that's obviously HTML. Even sprintf is an improvement: HTML = sprintf("%s", htmlClean(link), htmlClean(description));

  • Anthony Martin (unregistered)

    The biggest WTF is using sb.toString() instead of new String(sb). What do you think sb.toString() does?

  • Someone (unregistered) in reply to Hit

    Actually. the Java spec explicitly states that "foo" + "foo2" + "foo3" is equivalent to "foofoo2foo3"

  • mjparme (unregistered)

    I see string concatenation in string buffers all the time. IntelliJ will actually warn you about this and fix it for you.

    I think the Java compiler probably converts it to a StringBuffer any way though. (I remember reading something about this once).

  • Anonymous coward (unregistered) in reply to Jack Moxley
    Why why why use StringBuffers
    StringBuilder was introduced with J2SE 1.5 - a lot of projects haven't been ported yet and a lot of clients still run 1.4.
  • Krasna Halopti (unregistered) in reply to Anthony Martin

    On my system, new String(sb) does more work than calling sb.toString():

    public String(StringBuffer buffer) {
        String result = buffer.toString();
        this.value = result.value;
        this.count = result.count;
        this.offset = result.offset;
    }
    
  • Joost (unregistered) in reply to Zylon
    Zylon:
    The real WTF is people who casually drop "pattern" references in an attempt to sound like supar smarty programmer man.

    Ouch! Please respect me again, Random Stranger Named Zylon! I don't REALLY think the printf pattern is a design pattern, you know!

  • David Vallner (unregistered) in reply to MrBester
    MrBester:
    As for sentence 2: variable case attributes and whitespace between the attribute name and = are typical of the "can't be bothered as IE parses it anyway" approach to HTML

    Aren't those valid HTML 4? At least the case-sensitivity.

    (Bias disclaimer: I think making xhtml case-sensitive was a gruesomely stupid idea.)

  • James (unregistered)

    This brings up a good point I've been meaning to make for a while: I think it would be nice if each WTF post ended with a 2 or 3 sentence explanation of why it's a WTF, even if it's horribly, painfully obvious to 99% of the target audience. I've written a bit of Java before, but haven't worked much with JSP/Servelets, so I'm not really sure what the "right" way to do this is -- and based on the previous discussion above, it seems like there's not even really a consensus. So a short "here's what went wrong" would do a lot to help greenhorns like myself learn something from WTFs like this one.

  • Eggbert (unregistered)

    Frankly guys, your comments about optimization don't hold water... Java takes care of converting "+" to StringBuffer.append() internally... and if you are coding for 1.4 and not 1.5, the faster StringBuilder is not available, so there's nothing at all lost... and readability is greatly improved.

    I'd can much more easily scan:

    "abcde"+var1+"ghijk"+var2;

    than:

    sb.append("abcde").append(var1).append("ghijk").append(var2);

    Or, to quote directly from the StringBuffer doc:

    String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

    x = "a" + 4 + "c"

    is compiled to the equivalent of:

    x = new StringBuffer().append("a").append(4).append("c").toString()

  • Jeff Conrad (unregistered)

    For JavaScript, you can achieve performance by changing += string builds to building an Array(), then using the array.join("") to build the result string. The best speed (ms) depends on the size of the individual String lines you are concatting. When the string lines are too small, you lose performance using the Array method. Making the individual lines 100-500 bytes was the most effective size.

  • Mike (unregistered)

    This is fine style. Might be a little inefficient to build up little string to be appended but it's certainly better then the alternative:

    StringBuffer sb = new StringBuffer(); sb.append("<input type="TEXT" name= "" + cellName); sb.append("" value="" + cellValue + "" "); sb.append("popupStyle="omni" ");

    versus

    String s = ""; s += "<input type="TEXT" name= "" + cellName; s += "" value="" + cellValue + "" "; s += "popupStyle="omni" ";

    The latter would build progressively longer temp strings.

    BTW - if this is Java 1.5 he should be using StringBuilder in place of StringBuffer.

  • Guy Geens (unregistered)

    On my previous project, I came across the following:

    private static StringBuffer QUERY = new StringBuffer()
              .append("SELECT * ")
              .append("FROM mytable ")
              .append("WHERE id = ?");
    

    (The actual query was longer than this.)

    Then, in the code:

      prepareStatement(QUERY.toString());
    

    Apparently, the developer wanted to make the query more readable by splitting it in smaller chunks. He also heard that String concatenation was expensive, so he used a StringBuffer.

    In the end, he got 2 performance penalties for the price of one.

  • darwin (unregistered) in reply to csixty4
    csixty4:
    Does he believe that XML is "nothing but specially formatted strings", and that org.w3c.dom is what wannabe programmers use to build or parse it?

    You mean it isn't? I sure wish someone had told some of the devs who preceeded me on my current project that!

  • Mike G (unregistered)

    i was just fixing a very similar abuse of .NET's StringBuilder class in one of my ex-coworkers code just before i took a break to read this.

  • Volodya (unregistered)

    I know i might upset everybody here, but any time i have to return a string from a function, i create result in StringBuffer, and then return that. I don't see WTF in this one.

Leave a comment on “String Optimizations in Java”

Log In or post as a guest

Replying to comment #:

« Return to Article