0

I was trying to figure out best way to concatenate Strings in java. So I tested three approaches and was surprised by the results. These are the three approaches

private static String test1(String delimiter, String... data) {
    StringBuilder sb = new StringBuilder();
    for (String s : data) {
        sb.append(s);
        sb.append(delimiter);
    }
    return sb.replace(sb.length() - delimiter.length(), sb.length(), "").toString();
}

private static String test2(String delimiter, String... data) {
    String join = "";
    for(String s : data)
        join += s + delimiter;
    return join.substring(0, join.length() - delimiter.length());
}

private static String test3(String delimiter, String... data) {
    return String.join(delimiter, data);
}

tested this input with and "," as delimiter:

String[] data = new String[100000];
Arrays.fill(data, "*");

Test bench: Core i5 2.2ghz, 8gb ram, 256gb ssd, Windows 7 Results averaging around:

  1. test1 -> 10ms
  2. test2 -> 18038ms
  3. test3 -> 17341ms

test2 result is obvious, but test3 should have performed nearly as good as test1 as it is roughly the same code underneath. So I tested with another bench and was surprised again.

Test bench2: Core i5 1.6ghz, 4gb ram, 128gb ssd, OSX El-Capitan

Results averaging around:

  1. test1 -> 9ms
  2. test2 -> 7171ms
  3. test3 -> 9ms

What is the reason for this strange behavior? And why is it that lower specs of bench2 performing better(In case of test2)?


My question is not about StringBuilder vs String concat. It's why is there a huge difference in running times of same code on different OSes? String.join(....) is taking as much time as String concat on windows and StringBuilder on OSX

public static void main(String[] args) {
    String[] data = new String[100000];
    Arrays.fill(data, "*");

    long now = System.currentTimeMillis();
    test1(",", data);
    System.out.println("test1->" + (System.currentTimeMillis() - now) + "ms");

    now = System.currentTimeMillis();
    test2(",", data);
    System.out.println("test2->" + (System.currentTimeMillis() - now) + "ms");

    now = System.currentTimeMillis();
    test3(",", data);
    System.out.println("test3->" + (System.currentTimeMillis() - now) + "ms");
}

private static String test1(String delimiter, String... data) {
    StringBuilder sb = new StringBuilder();
    for (String s : data) {
        sb.append(s);
        sb.append(delimiter);
    }
    return sb.replace(sb.length() - delimiter.length(), sb.length(), "").toString();
}

private static String test2(String delimiter, String... data) {
    String join = "";
    for(String s : data)
        join += s + delimiter;
    return join.substring(0, join.length() - delimiter.length());
}

private static String test3(String delimiter, String... data) {
    return String.join(delimiter, data);
}
Haunter
  • 1
  • 3

0 Answers0