5 Replies Latest reply: Mar 30, 2009 1:05 PM by jschellSomeoneStoleMyAlias RSS

    Concatenating strings

    807588
      Hi

      I know that concatenating strings using the '+' operator is a expensive operation -if your application is big- so I want to do it using string buffers but I would like to do the building of the string in a new method so I can control the logging better and do another common tasks if neccesary but I do this by creating a static method that receives a String array:

      Util.buildString(String[] subStrings)

      inside it:

      StringBuffer sb = new StringBuffer();
                for (int i = 0; i < subStrings.length; i++) {
                     sb.append(subStrings);
                }
                return sb.toString();

      My question is that I would like to know if doing the string like this 'better' at processor's time and memory costs or no, because I usually have to build a new String[]{substring_1, substring_2....., substring_n} to call this method.

      Util.buildString(new String[]{substring_1, substring_2....., substring_n})

      I think that it internally will do an array of pointers to existing strings so it should have better performance but i'm not sure and I would like to know your opinion -or The Thruth-.
        • 1. Re: Concatenating strings
          807588
          The '+' operator isn't that inefficient because the application is big. It's only noticeable if it's used many times like in a loop. If you have few enough strings that you can write them all out in a method call, neither way is going to have much of a difference in processing time.

          Your way might execute slightly faster because creating an array is faster than creating many temporary strings, unless the JVM optimises these operations (I think the compiler will convert a sequence of concatenations to use a StringBuilder). I would still just use the '+' operator here because it's simpler.

          You can check efficiency yourself by timing how long a method takes to run many times in a loop, using the java date/time classes.
          • 2. Re: Concatenating strings
            807588
            StringBuilders seem intimidating, but it turns out they're very simple!!!

            StringBuilder sbX = new StringBuilder(256);
            sbX.append("Something");
            sbX.append(" else");
            sbX.append(" entirely.");
            System.out.println("sbX.toString() );
            String sFinished = sbX.toString();

            As long as the StringBuilder variable is scoped properly, you could move the append process to a separate routine, and then do whatever you wanted in that routine.

            // declare in your class
            StringBuilder sbX = null;
            ...

            (inside some other routine)
            sbX = new StringBuilder(256);

            sbConcatenate("Something");
            sbConcatenate(" else");
            sbConcatenate(" entirely.");

            ...

            private void sbConcatenate(String sX) {
            sbX.append(sX);

            // do any other loggin operation you want here
            }
            • 3. Re: Concatenating strings
              jschellSomeoneStoleMyAlias
              noway wrote:
              Hi

              I know that concatenating strings using the '+' operator is a expensive operation -if your application is big- so I want to do it using string buffers but I would like to do the building of the string in a new method so I can control the logging better and do another common tasks if neccesary but I do this by creating a static method that receives a String array:

              Util.buildString(String[] subStrings)

              inside it:

              StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < subStrings.length; i++) {
                             sb.append(subStrings);
                        }
                        return sb.toString();

              My question is that I would like to know if doing the string like this 'better' at processor's time and memory costs or no, because I usually have to build a new String[]{substring_1, substring_2....., substring_n} to call this method.

              Util.buildString(new String[]{substring_1, substring_2....., substring_n})

              I think that it internally will do an array of pointers to existing strings so it should have better performance but i'm not sure and I would like to know your opinion -or The Thruth-.

              The truth is that most of the time you should not consider it.

              Overuse of the idiom leads to hard to read and thus maintain code. Overuse could even potentially be less efficient.

              As noted by the other poster there are time when string construction will have a heavy cost. With experience you can spot those. Invariably it is only situations where 'loops' are involved where instructions are known to be called tens or hundreds of thousands of times.

              However, until you have the experience it is much better to rely on profiling (automated or manual) to actually find bottlenecks in your application.

              You mentioned "logging" in the above but didn't seem to address it further. However if you are concerned about situations like the following.
                    log.Debug("Something: " + var + " " + " other=" + otherVar);
              Then the following pseudo code is much more efficient than doing anything with StringBuilder
                    if (log.IsLogLevel(Logger.Debug))
                         log.Debug("Something: " + var + " " + " other=" + otherVar);
              StringBuffer sb = new StringBuffer();
              Use StringBuilder rather than StringBuffer unless you have a specific need for the latter.
              • 4. Re: Concatenating strings
                807588
                Well, I dont use stringbuilders because i must use jdk 1.4 and string builder was introduced in the 5.0.

                Also I wanna do in that mode cause is a new part in a existing aplication so NOW I CAN DO IT, and i dont see it less readable than the other way (the strings that I make in that way are VERY large, so unreadables or used a lot of times)

                Thanks all.
                • 5. Re: Concatenating strings
                  jschellSomeoneStoleMyAlias
                  noway wrote:
                  Well, I dont use stringbuilders because i must use jdk 1.4 and string builder was introduced in the 5.0.
                  Then be aware that you certainly do not want to use it in situations where it would have not been used in the first place.
                  Also I wanna do in that mode cause is a new part in a existing aplication so NOW I CAN DO IT, and i dont see it less readable than the other way (the strings that I make in that way are VERY large, so unreadables or used a lot of times)
                  The following would not be helped either in readability and certainly not in efficiency by using StringBuilder.
                    .
                    String s = ""
                                + " some stuff"
                                + .... 100 lines
                                + " last line"