I found comments about avoiding strings for the comparison of values (especially in loops) in a few books because string comparison is a lot slower (using std::string). But why exactly is that?
Is it because integer units in the cpu are working faster?
Strings should be in byte I guess, so wouldn't a byte comparison do the job equally?
Thanks!
2, but in general int comparison is way faster than string.
If you want to compare their string values, then you should convert the integer to string before comparing (i.e. using String. valueOf() method). If you compare as integer values, then 5 is less than "123". If you compare as string values, then 5 is greater than "123".
Time Complexity: O(min(n,m)) where n and m are the length of the strings. Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
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.
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.
The compiler can optimize integer comparisons to happen directly inside the cpu registers.
Vaguely speaking, string comparison requires n number of integer comparison where n is the size of string, whereas integer comparison is just one comparison if you think ratio-wise. It's a rough idea of what might be going when comparing strings!
So obviously string comparison would be a slower process, since it's n number of integer comparisons (approx).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With