性能优化解决方案
如果您关心性能和微观优化,请检查此一行代码:
function no_dupes(array $input_array) {
return count($input_array) === count(array_flip($input_array));
}
描述:
该函数比较$input_array
中的数组元素数与array_flip的元素数。值变为键,而在关联数组中,键必须是唯一的,因此不唯一的值将丢失,最终元素数比原始元素数低。
警告:
如手册所述,数组键只能是类型为int
或string
,因此您必须在原始数组值中具有相同的类型以进行比较,否则PHP将开始进行强制类型转换并产生意外结果。请参见https://3v4l.org/7bRXI的示例以了解此异常情况的失败模式。
针对包含1000万条记录的数组的证明:
测试用例:
<?php
$elements = array_merge(range(1,10000000),[1]);
$time = microtime(true);
accepted_solution($elements);
echo 'Accepted solution: ', (microtime(true) - $time), 's', PHP_EOL;
$time = microtime(true);
most_voted_solution($elements);
echo 'Most voted solution: ', (microtime(true) - $time), 's', PHP_EOL;
$time = microtime(true);
this_answer_solution($elements);
echo 'This answer solution: ', (microtime(true) - $time), 's', PHP_EOL;
function accepted_solution($array){
$dupe_array = array();
foreach($array as $val){
if(!isset($dupe_array[$val])){$dupe_array[$val]=0;}
if(++$dupe_array[$val] > 1){
return true;
}
}
return false;
}
function most_voted_solution($array) {
return count($array) !== count(array_unique($array));
}
function this_answer_solution(array $input_array) {
return count($input_array) === count(array_flip($input_array));
}
请注意,在巨大数组的开头存在非唯一值时,被认可的解决方案在某些情况下可能会更快。
if(count($array) == count(array_unique($array)))
是最好的选择。你必须以这种或那种方式遍历数组,而我认为内置函数已经对此进行了优化。array_flip
也可以考虑使用。 - Felix Kling