如果您需要最佳性能,您需要将数据存储为数组键,并使用
isset
或
array_key_exists
(
自php >= 7.4以来,array_key_exists
与isset
一样快)而不是使用
in_array
。
注意。在哈希映射上使用isset比在数组中搜索值(in_array)更快确实是正确的,但请记住,将值数组["foo", "bar", "baz"]转换为哈希映射["foo" => true, "bar" => true, "baz" => true]会产生内存成本(以及可能构建哈希映射,这取决于您何时以及如何进行操作)。像所有事物一样,您必须权衡每种情况的利弊,确定哈希映射或值数组(列表)对您的需求最有效。这不仅适用于PHP,而且是计算机科学的一个通用问题领域。
以下是一些来自https://gist.github.com/alcaeus/536156663fac96744eba77b3e133e50a的性能测试。
<?php declare(strict_types = 1);
function testPerformance($name, Closure $closure, $runs = 1000000)
{
$start = microtime(true);
for (; $runs > 0; $runs--)
{
$closure();
}
$end = microtime(true);
printf("Function call %s took %.5f seconds\n", $name, $end - $start);
}
$items = [1111111];
for ($i = 0; $i < 100000; $i++) {
$items[] = rand(0, 1000000);
}
$items = array_unique($items);
shuffle($items);
$assocItems = array_combine($items, array_fill(0, count($items), true));
$in_array = function () use ($items) {
in_array(1111111, $items);
};
$isset = function () use ($assocItems) {
isset($items[1111111]);
};
$array_key_exists = function () use ($assocItems) {
array_key_exists(1111111, $assocItems);
};
testPerformance('in_array', $in_array, 100000);
testPerformance('isset', $isset, 100000);
testPerformance('array_key_exists', $array_key_exists, 100000);
输出:
Function call in_array took 5.01030 seconds
Function call isset took 0.00627 seconds
Function call array_key_exists took 0.00620 seconds
in_array
才是罪魁祸首,而不是Functions::generate_machine_id()
吗? - decezeFunctions::generate_machine_id
的代码吗? - cHao