I'm trying to compare two 10,000 bytes string and it takes lot of time...Is there a fastest way to compare?
Asked
Active
Viewed 2,028 times
-2
-
2It would be helpful to share how you're comparing them. – Joe Day Oct 11 '12 at 14:23
-
1possible duplicate of [Python string comparison pointing to the result](http://stackoverflow.com/questions/12840451/python-string-comparison-pointing-to-the-result) – mgilson Oct 11 '12 at 14:24
-
woudln't say duplicate, just the line right after the one we just answered :). What do you call compare, what time does it take, what is your current code. . . – jlengrand Oct 11 '12 at 14:29
-
3If you're only comparing once, it shouldn't take too long. Also, by `compare`, what do you mean? Are you only checking equality? Do you need other information from the comparison (as in your previous question?). Please show us the code you are using, and we'll attempt to optimize it for you. – mgilson Oct 11 '12 at 14:29
-
No, _comparing_ strings does _not_ take a lot of time. Actually even writing in C you can't do much better, since python calls memcmp to compare byte strings. Maybe you are applying regexes on them and doing some stuff to obtain a "comparison" result? In that case probably your regex can be optimized, or the actions you are doing are inefficient. Without any hint we are stuck using the crystal ball instead of analyzing your problem. – Bakuriu Oct 11 '12 at 14:45
-
@Bakuriu -- You might actually even do better in python because I assume it does an int compare on the length before comparing the string data (since python strings know their length)... – mgilson Oct 11 '12 at 14:47
-
By the way, if the author is the same as in [this](http://stackoverflow.com/questions/12840451/python-string-comparison-pointing-to-the-result) question then he's probably looping at "python level", which probably is a lot slower than plain string comparison(but without more information everything is just a guess). – Bakuriu Oct 11 '12 at 14:56
1 Answers
5
The fastest way to compare two strings in Python will always be:
if s1 == s2:
print "strings are equal"
If you have other constraints, you'll need to state them explicitly.

Peter Mortensen
- 30,738
- 21
- 105
- 131

mgilson
- 300,191
- 65
- 633
- 696