String comparison

Asked

Viewed 6,374 times

5

There are several ways of comparison, but I always see that the most suitable are (===, strcmp ou strcasecmp).

Among these forms presented considered the safest (according to some websites on the Internet), follow the doubts:

  1. Which would be the most suitable for use?
  2. What’s the difference between them?
  3. There is also some difference in performance?

2 answers

8


You are referring to different approximations. Although both compare two strings what they return (or say about the strings) is different.

=== returns only a Boolean, true or false.

strcmp return negative (<0) if the first string passed to the function is less than the second; positive otherwise; and zero if they are equal.

It can be said that === is to know if they are identical, and strcmp is to compare strings returning 3 possibilities. strcasecmp is a variant of strcmp but case-insensitive, ignoring whether it has large or small letters.

Performance:

It is only possible to compare performance differences in the case that both have in commun, that is when you want to compare if two strings are identical.

Thus, bearing in mind that strcmp and strcasecmp need one more check to know the result it is obvious that === is faster. Or are strcmp run first strcmp(strA, strB) and then have one more equality check == 0. However I found some numbers here which point to faster 3x performance using ===.

Completion:

If you want to know if two strings are identical you should use ===.

  • Do you know if there is any difference in performance between them?

  • @Rafaelwithoeft added more info on the answer.

-5

Use === if you want to know if they are identical.

If you want to know which is the largest of which user strcmp.

Don’t be alone in this post always go as far as you can in knowledge.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.