Home >Backend Development >PHP Problem >Why is === faster than ==?

Why is === faster than ==?

Guanhui
Guanhuiforward
2020-06-18 18:01:322928browse

Why is === faster than ==?

Comparison operators == (equality operator) and === (identity operator) are used for comparison two values. They are also known as the Loose equals (==) and Strict equals (===) operators.

Symbol Name Example Output result
== Equals $a == $b Ignore the type, TRUE if $a is equal to $b
=== Constantly equal to $a === $b TRUE if $a is equal to $b and the type is the same

PHP Operators There are many operators in PHP, but the == and === operators perform similar tasks strictly or arbitrarily.

  • If the two values ​​are of different types, then == and === will get different results. The speed of the operation will also vary because == performs a type conversion first and then performs the comparison.
  • If the two value types are the same, then == and === will get the same result. The operation speed is also almost the same, and neither operator performs type conversion.

Equality operation == will temporarily convert the data type when comparing two values, while === (identical operator) does not need to perform any type conversion, so the calculation amount is reduced and the speed is faster .

Case 1:

<?php 

// 0 == 0 ->  类型相同返回 true
// 转换完成,然后
// 检查是否相等
var_dump(0 == "a"); 

// 1 == 1 -> true 
var_dump("1" == "01"); 

// 10 == 10 -> true 
var_dump("10" == "1e1"); 

// 100 == 100 -> true 
var_dump(100 == "1e2"); 

// 0 === "a" -> 这种情况为 false
// 转换不仅完成
// 还检查是否存在
// 是否相等
var_dump(0 === "a"); 

// "1" === "01" -> false 
var_dump("1" === "01"); 

// "10" === "1e1" -> false 
var_dump("10" === "1e1"); 

// 100 == "1e2" -> false 
var_dump(100 === "1e2"); 

switch ("a") { 
case 0: 
    echo "In first case"; 
    break; 

// 永远不会匹配 "a" 选项
// 因为 switch 使用的是 == 
case "a": 
    echo "In sceond case"; 
    break; 
} 
?>

Output:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
In first case

Case 2:

<?php 

// TRUE - 以下表达式等同于 (bool)1 == TRUE 
var_dump(1 == TRUE); 

// TRUE - 以下表达式等同于 (bool)0 == FALSE 
var_dump(0 == FALSE); 

// FALSE - 1 不全等于 TRUE
// 1 是整形, TRUE 是布尔型 
var_dump(1 === TRUE); 

// FALSE - 0 不全等于 FALSE
// 0 是整形, FALSE 是布尔型
var_dump(0 === FALSE); 
?>

Output:

bool(true)
bool(true)
bool(false)
bool(false)

Note: === operator 'type comparison is relatively safe', will only return TRUE when two values ​​have the same type and value, use == will return TRUE if the values ​​are equal.

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of Why is === faster than ==?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete