array_key_exists($key, $array) vs !empty($array[$key])

前端 未结 4 1499
清酒与你
清酒与你 2021-01-01 18:09

I\'ve seen a lot of people do the former, is there any performance benefit doing one vs the other? Or is it just an eye candy? I personally use the latter every time as it i

4条回答
  •  情话喂你
    2021-01-01 18:52

    The other responses focus on the differences between the two functions. This is true, but if the source array does not contain null or 0 or "", ... (empty values) values you can benchmark the speed of the two functions:

    Which gave me the following results:

    For a small array:

    • array_key_exists: float(0.18357992172241)
    • empty: float(0.072798013687134)
    • isset: float(0.070242881774902)

    For a relative big array:

    • array_key_exists: float(0.57489585876465)
    • empty: float(0.0068421363830566)
    • isset: float(0.0069410800933838)

    So if it's possible it's faster to use empty or isset.

提交回复
热议问题