php - in_array() 性能优化

标签 php performance optimization

我有以下条件:

if(in_array($needle, $haystack) ||
    in_array($needle . "somePostfix", $haystack) ||
    in_array($needle . "someOtherPostfix", $haystack) ||
    // and some more) {
    // do something
}

我的 haystack 包含超过 10k 个元素,这个检查大约需要 400ms。我知道 in_array 必须多次遍历整个数组。在我的例子中,常见的情况是找不到元素。我试图通过创建以下只在大海捞针上迭代一次的方法来改进这一点:

function wildcardInArray($needle, $haystack) {
    foreach ($haystack as $value) {
        if (true === fnmatch($needle . '*', $haystack)) {
            return true;
        }
    }
    return false;
}

但这会进一步降低我的性能,在我看来 fnmatch 是瓶颈。

这种数组搜索的情况有什么改进吗?

最佳答案

您可以将数组用作“键”,即:

$arr = ['a', 'b', 'c', …];$arr = ['a' => true, 'b' => true , …]

您将消耗更多内存,但使用 isset($arr[$key]); 会立即得到结果。

最快但内存最大,可以使用 stdClass 和 isset($obj->$key);

$obj = new stdClass();
$obj->{'a'} = true;
$obj->{'b'} = true;
$obj->{'…'} = true;

如果您不能更改数组结构,请告诉我们您是否可以手动对数组内容进行排序?

// generic
$length = strlen($needle);
$char = $needle[0];
$found = false;
$suffixes = [ false, 'somePostfix', 'someOtherPostfix' ];

foreach($haystack as $entry) {
  if ($char === $entry[0] && $needle === substr($entry, 0, $length)) {
    $suffix = substr($entry, $length);
    if (in_array($suffix, $suffixes, true)) {
      $found = true;
      break;
    }
  }
}

关于php - in_array() 性能优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205363/

相关文章:

javascript - 我该如何更有效地提供基于文本的网页?

php - 自动填写 HTML 表单中的文本输入

php - Laravel、依赖注入(inject)和 Eloquent

java - 不同的屏幕尺寸

python - 确定性退火法

case 值为reinterpret_cast(string) 的 C++ switch 语句

php - 如何保存 Doctrine2 实体

php - laravel pgsql 中的 failed_jobs 表

algorithm - 忽略样式偏好,拥有一个强大的循环与许多轻量级循环相比有什么优势吗?

asp.net - asp.net中如何避免对数据库进行过多的查询?