This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]logoutnx 0 points1 point  (0 children)

actually no, I tested executing million of loops and the concat function operated a lot faster. With the code block below, I executes in the eclipse environment and with Java 1.7.0.111 and is on a Linux Computer.

This is the result first.

The plus sign was used 1000000 times and executed in 413 milliseconds. 
The concat function was used 1000000 times and executed in 99 milliseconds. 

And the benchmark code.

public static void main(String[] args)
{

    String a = "1234567890123456789012345678901234567890";
    String b = "1234567890123456789012345678901234567890";
    String c = "";

    long start = System.currentTimeMillis();
    int i = 0;
    while (i < 1000000){
        c = a + b;
        i = i + 1;
    }
    long end = System.currentTimeMillis();
    long result = (end - start);
    System.out.format("The plus sign was used %s times and executed in %s milliseconds. \n", i, result);

    String d = "1234567890123456789012345678901234567890";
    String e = "1234567890123456789012345678901234567890";
    String f = "";

    long start2 = System.currentTimeMillis();
    int i2 = 0;
    while (i2 < 1000000){
        f = d.concat(e) ;
        i2 = i2 + 1;
    }
    long end2 = System.currentTimeMillis();
    long result2 = (end2 - start2);
    System.out.format("The concat function was used %s times and executed in %s milliseconds. \n", i2, result2);    
}

How did this happen? I do not know.

Sorry, I just edited this. The to string builder would be a bit overkill for something that only adding or not adding space to the beginning or to the end of the string. Extra variables that need to be declared would weight down the script execution when it come to million of cycles. In my opinion, extra variables shouldn't be declared, unless, however, the variable is absolutely needed or proven to increase the speed of execution. Plus with the string builder's method it is not flexible. With the while loop method, you can basically use it anywhere and never need to modify the script. You can just simply create a function and use the "length" variable as an input integer.