doule6314 2017-01-04 03:19
浏览 50
已采纳

PHP:不等于和不相同的运算符如何工作,它们比等于或相同的运算符更快?

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条回答 默认 最新

  • dongtuliao6760 2017-01-04 04:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记