Reputation: 155
I'm doing a check in a loop to see if a string equals another string. Easy stuff.
However, it seems that I keep adding to the strings to check against, and have like ten different strings I'm checking against with each loop through. It's easier code wise to just create an array of the strings to check against, and then do in_array();, but I was wondering which would parse faster and use less system resources?
Array
$hideme = array(".", "..", "Thumb.db", "index.php", "icons", "index_backup.php",
"style.css", "highlighter.css", "highlighter.js", "users");
if (!in_array($sub, $hideme)) {
String != String
if ($sub != "." && $sub != ".." ...etc
The difference is probably negligible, just curious for future reference.
Upvotes: 1
Views: 845
Reputation: 2613
The easiest solution (and perhaps the fastest) that will easily scale if your $hideme array gets big is to use isset().
$hideme = array(".", "..", "Thumb.db", "index.php", "icons", "index_backup.php",
"style.css", "highlighter.css", "highlighter.js", "users");
if (!isset($hideme[$sub])) {
// $sub is not in $hideme
}
For small arrays, in_array works fine but is generally slower and can become too slow if your array is large.
Upvotes: 0
Reputation: 26699
The build-in function are always faster, as they are compiled C code. The PHP code must be interpreted.
If you really care about CPU cycles, isset() is fastest, so setting the possible values as array keys will be fastest way. Of course, there is CPU vs memory usage, so which use less system resources depends on which resources you want to save.
As @Kendall Frey stated, this is micro-optimization, so keep code readable and don't do anything about optimization, unless profiler shows that this code has large impact on the execution.
Upvotes: 1
Reputation: 44316
Use the first one. There won't be much of a difference in speed, but readability is the real difference.
CPU cycles are cheap. Programmer hours are not.
Upvotes: 6