Is it efficient to compare a string with another string or string literal like this?
string a;
string b;
if (a == "test")
or
if (a == b)
My coworker asked me to use memcmp
Any comments about this?
Thanks.
C strcmp() In this tutorial, you will learn to compare two strings using the strcmp() function. The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
Yes use a == b
, do not listen to your co-worker.
You should always prefer code readability and using STL over using C functions unless you have a specific bottleneck in your program that you need to optimize and you have proven that it is truly a bottleneck.
Obviously you should use a == b
and rely on its implementation.
For the record, std::char_traits<char>::compare()
in a popular implementation relies on memcmp()
, so calling it directly would only be more painful and error-prone.
If you really need to know, you should write a test-application and see what the timing is.
That being said, you should rely on the provided implementation being quite efficient. It usually is.
I think your coworker is a bit hooked up on possible optimization.
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