Check to see if a string is exists in a dataset of strings.
Link to the blog post about this test.
(To understand this test better I suggest you read the blog post, link above) Using 3 different methods I check to see if a certain value exists in a previous defined set of values.
I'm doing 10000 iterations.
Title | first value | mid value | last value | no hit | Avarage | Difference |
in_array | 0.001891 | 0.001833 | 0.001882 | 0.001879 | 0.001871 | 100.00% |
strpos | 0.000285 | 0.000317 | 0.000412 | 0.000429 | 0.000361 | 19.28% |
isset in array | 0.000159 | 0.000164 | 0.000160 | 0.000158 | 0.000160 | 8.56% |
The winner is without a doubt isset.
<?php
// --- Informative block
$title = "Look for a value";
$teaser = "Check to see if a string is exists in a dataset of strings.";
$description = "(To understand this test better I suggest you read the blog post, link above) Using 3 different methods I check to see if a certain value exists in a previous defined set of values.<br /> I'm doing 10000 iterations.";
$conclusion = "The winner is without a doubt isset.";
$link = "http://birk-jensen.dk/2010/12/checking-for-a-value/";
// --- Actual test
if ( isset($runTest) ) {
// -- Initialize the test
require_once(dirname(__FILE__) . "/../Bench.php");
$b = new Bench();
$stylesA = array("none", "hidden", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset", "inherit");
$stylesS = "none hidden dotted dashed solid double groove ridge inset outset inherit";
$stylesK = array_flip($stylesA);
$checkFor = array("none", "solid", "inherit", "nohit");
$it = 10000;
$headers = array("first value", "mid value", "last value", "no hit");
$dontSave = true;
// Check in_array first
for ($cf = 0; $cf < count($checkFor); $cf++) {
$res = (in_array($checkFor, $stylesA) === true);
$b->start("in_array", $checkFor[$cf]);
for ($i = 0; $i < $it; $i++) {
$res = (in_array($checkFor, $stylesA) === true);
}
$b->end("in_array", $checkFor[$cf]);
$res = (strpos($stylesS, $checkFor[$cf]) !== false);
$b->start("strpos", $checkFor[$cf]);
for ($i = 0; $i < $it; $i++) {
$res = (strpos($stylesS, $checkFor[$cf]) !== false);
}
$b->end("strpos", $checkFor[$cf]);
$res = (isset($stylesK[$checkFor[$cf]]) === true);
$b->start("isset in array", $checkFor[$cf]);
for ($i = 0; $i < $it; $i++) {
$res = (isset($stylesK[$checkFor[$cf]]) === true);
}
$b->end("isset in array", $checkFor[$cf]);
$dontSave = false;
}
}