Total Pageviews

2018/05/07

[Java] Use Apache Commons StringUtils.Replace Instead of String.replace

Quote
In general, the String.replace method works fine and is pretty efficient, especially if you’re using Java 9. But if your application requires a lot of replace operations and you haven’t updated to the newest Java version, it still makes sense to check for faster and more efficient alternatives.

Here has a simple experiments:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package your.simple.java;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

public class StringReplacementTest {

    private String test = "test";
    private int count = 100000000;

    public static void main(String[] args) {
        new StringReplacementTest().test1();
        new StringReplacementTest().test2();
    }

    public void test1() {
        Date from = Calendar.getInstance().getTime();
        for (int i = 0; i < count; i++) {
            test.replace("test", "simple test");
        }

        Date to = Calendar.getInstance().getTime();
        long seconds = (to.getTime() - from.getTime()) / 1000;
        System.out.println("[test1] seconds = " + seconds);
    }

    public void test2() {
        Date from = Calendar.getInstance().getTime();
        for (int i = 0; i < count; i++) {
            StringUtils.replace(test, "test", "simple test");
        }

        Date to = Calendar.getInstance().getTime();
        long seconds = (to.getTime() - from.getTime()) / 1000;
        System.out.println("[test2] seconds = " + seconds);
    }

}


Execution result:
[test1] seconds = 56
[test2] seconds = 9


Reference
[1] https://dzone.com/articles/11-simple-java-performance-tuning-tips?edition=334833&utm_source=Daily%20Digest&utm_medium=email&utm_campaign=Daily%20Digest%202017-11-03

No comments: