简体   繁体   中英

String comparison performance in java

I have two Strings of about 15 character in java and I want to know how many flops or cycles does it take to compare these two. how can I acquire such information.

example :

"Hello World".compareTo("Another Hello World")

I don't know how to answer that in terms of flops or cycles, but in terms of what's actually being done when you call compareTo , the actual processing depends on the number of identical characters the two Strings share in their beginning, since compareTo will only test as many characters as required to find the first non-equal character.

In your example, only the first character of the two Strings will be examined (since 'H' != 'A'). In the worst case, if the two Strings are equal, all characters of both Strings will be compared.

I want to know how many flops or cycles does it take

I assume you are interested in CPU cycles/timings.

To measure CPU time per thread under windows you can use GetThreadTimes WinAPI function, you can wrap its call using JNI.

To get cycles you will want to use QueryThreadCycleTime function.

Both will return times/cycles per thread, so even if some other JVM thread will take CPU during measurement, it will not be included in results.

EDIT:

It looks like per thread timing is available since 1.5:

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBean.html

java.lang.String class source is available. For example in JRE 1.6.0_38 it is implemented in following way:

public int compareTo(String anotherString) {
    int len1 = count;
    int len2 = anotherString.count;
    int n = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;

    if (i == j) {
        int k = i;
        int lim = n + i;
        while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
        }
    } else {
        while (n-- != 0) {
        char c1 = v1[i++];
        char c2 = v2[j++];
        if (c1 != c2) {
            return c1 - c2;
        }
        }
    }
    return len1 - len2;
}

It is O(n) where n is the number of matching chars in both strings. In the worst case where one string is prefix of the other n will be the length of the shorter string. For example "test".compareTo("testa").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM