PHP speed: what is faster? if (isset ($foo)) OR if ($foo==true) [closed]
I am just trying to optimize my code.
I need to prefill a form with data from a database, and I need to check if the variable exist to fill the text box (I don't like the @
error hiding).
The form is really long, then I need to check multiple times if the variables exist.
What is faster of the following two?
if (开发者_如何学JAVAisset ($item))
if ($item_exists==true)
Or even
if ($item_exists===true)
With a for
loop repeating it 10000000 times the same script took:
if (isset ($item))
2.25843787193if ($item_exists==true)
6.25483512878if ($item_exists===true)
5.99481105804
So I can tell isset
surely is faster.
In this case you shouldn’t ask about performance but about correctness first. Because isset
does not behave like a boolean convertion and comparison to true (see type comparison table). Especially the values ""
(empty string), array()
(empty array), false
, 0
, and "0"
(0
as a string) are handled differently.
I'm sure there is a performance difference; I'm sure it has been benchmarked somewhere; but I'm also sure it really doesn't matter at all for real-world purposes. Any achievable gain is in the milliseconds here, and what's much, much more important is the readability of the code, and the avoiding of warnings (which cost performance, whether output or not).
You will probably need isset
if you can't be sure it's set at the time you access it. type-safe comparison ===
shouldn't be necessary if $item_exists
always is a boolean, but it won't harm either. So depending on your situation, you may need
if ((isset($item)) and ($item_exists === true))
To answer though, most likely isset() and "===" will be fastest as they only check for one condition, where == checks for multiple conditions and be slower. I haven't officially tested this, but I think its right. @Pekka is also correct, if you are looking to optimize, these really aren't going to be where you do it. As it would probably take thousands of calls just to notice a few milliseconds of difference.
I would suggest the following alternatives:
if (@$item)
if (@$item_exists)
There is only one way to optimize your code, called "profiling". First you got to know what part of code requires optimization. And only then run tests, find solutions, etc.
The "circling" approach from the Marcx's answer is awful too. If you want to test if any code makes a real difference, test it from the browser's point of view, using the Apache benchmark utility.
精彩评论