Originally posted by Jon Dornback:
I am reading in input from a socket, and need to compare it to a string value. which is faster:
thanks in advance,
Jon
[ February 10, 2003: Message edited by: Jon Dornback ]
Hi Jon Dornback
You could
test it by doing a simple test like the following.
Here is the output I got on it.
Time for
method1 : method 2
0 : 20
0 : 20
0 : 0
10 : 0
0 : 0
0 : 0
0 : 10
0 : 0
0 : 0
10 : 0
0 : 0
Now here I stared noticing a few things.
A) if the byte[]'s are not the same then the Arrays.equals() method can be faster by first checking if the lenght of the two arrays are the same, if not they cannot contain the same data.
B) If the byte[]'s are large arrays and the first byte in each array differ the Arrays.equals() can stop checking them right there, but if they are simmilar except for the last byte in the array then it could take a bit more time to compare them.
Here is the code for String.equals()
Note 1 : This seems to speed thing up if the object being tested is not a String, but we know it is a String so this in not going to affect us.
Note 2 : This seems to be how I think they did it for in the Arrays.equals also, they first check the lenght of the String.
Note 3 : same as point B above... larger Strings will make more of a diffrence.
Thus I revised the code for the TestSpeed class to the following.
and Here is the outPut
Time for
method1 : method 2
10 : 40
40 : 30
10 : 10
20 : 0
10 : 10
10 : 10
20 : 10
10 : 10
10 : 10
10 : 20
10 : 10
Here is the code for the Arrays.equals();
So it seems that they are more or less the same code.
The funny thinging is that I'm thinking wouldn't it have been more OO if String.equals looked like this.