Why is integer comparison faster then string comparison?
With an integer, there exist instructions on the machine level which can perform a comparison in one cycle.
A string, however, consists of a lot of characters. In order to compare strings, you, in the worst case, have to look at every character of the strings.
In fact, when you compare strings, you're most likely using an integer comparison for each character in the string. You can probably see how this quickly can turn into a lot of comparisons as compared to comparing two integers.
Example: If you want to compare 1073741822 with 1073741823.
- String comparison: You have to compare each of the digits one by one. This is 10 comparisons, since the integers only differ by the last digit.
- Integer comparison: You can do this in one comparison, saving 9 comparisons as compared to the String comparison.
This is a bit simplified, naturally, but hopefully gets the point across.
The issue is that a string comparison isn't just a single comparison, it's a whole sequence of them in a loop. What do you expect to happen if you compare two strings that are each 10001 characters long and the first 9000 are the same?
BTW SSE makes string compare a LOT faster than one-character-at-a-time, but it can never reach the speed of an integer compare.