I am asking about comparing, let's say that I have 2 small texts:

  • abc: "This is a very long Text"
  • xyz: "xThis is a very long Text"

Does PHP compare every character or does it compare them as binary with masks?

As example abc !== xyz, if PHP compares them character-wise, then not-equal will be faster because it breaks after the first character?

I already read questions like: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

So I know that === is faster than == because of Casting.

But what is with === or == compared to !== or != ?

1

There are 1 answers

2
Gerrit0 On BEST ANSWER

Strings are defined as a structure here:

typedef struct {
    char *c;
    size_t len;
    size_t a;
} smart_string;

The equality operator is defined here. (The following three equality operators also perform in essentially the same way, except they skip the address check as it would always be false)

static zend_always_inline zend_bool zend_string_equals(zend_string *s1, zend_string *s2)
{
    return s1 == s2 || (ZSTR_LEN(s1) == ZSTR_LEN(s2) && !memcmp(ZSTR_VAL(s1), ZSTR_VAL(s2), ZSTR_LEN(s1)));
}

In case you don't speak C:

First, the address of each string structure is compared, if these are equal then the strings must be equal. Otherwise, further checks are made.

Second, if the addresses are not equal, then the length of each string is compared. This is just an integer equality check as the length is part of the string's structure definition. If the lengths are not equal, false is returned.

Next, the memory contents are checked for each string with memcmp. As memcmp returns 0 if the memory contents are equal, this is negated to return true.

To explicitly answer your question: PHP avoids checking every character of a string, the only case in which every character would be checked is that if every character of the string except for the last character is equal, and that the lengths of the strings are the same.

I must say: If you are really worrying about === being slower than !==, then you really shouldn't be.