array_unique() 是去重数组性能最好的内置函数。哈希表法自定义函数性能最优,哈希值用作键,值为空。循环法实现简单但效率低,建议使用内置或自定义函数进行去重。array_unique() 耗时 0.02 秒、array_reverse + array_filter() 耗时 0.04 秒、哈希表法耗时 0.01 秒、循环法耗时 0.39 秒。

引言
去重数组是指移除数组中重复的元素,保留唯一的值。PHP 提供了许多内置函数和自定义函数来执行此操作。本文将比较这些函数的性能,并提供实战案例。
内置函数
立即学习“PHP免费学习笔记(深入)”;
array_unique():内置函数,通过 哈希表 进行去重,效率较高。array_reverse() + array_filter():使用 array_reverse() 逆序数组,然后结合 array_filter() 移除重复元素。自定义函数
实战案例
假设我们有一个包含 100 万个整数的数组 $array。
$array = range(1, 1000000); $iterations = 100;
性能测试
function test_array_unique($array, $iterations) {
$total_time = 0;
for ($i = 0; $i < $iterations; $i++) {
$start_time = microtime(true);
$result = array_unique($array);
$end_time = microtime(true);
$total_time += $end_time - $start_time;
}
$avg_time = $total_time / $iterations;
echo "array_unique: $avg_time seconds\n";
}
function test_array_reverse_array_filter($array, $iterations) {
$total_time = 0;
for ($i = 0; $i < $iterations; $i++) {
$start_time = microtime(true);
$result = array_filter(array_reverse($array), 'array_unique');
$end_time = microtime(true);
$total_time += $end_time - $start_time;
}
$avg_time = $total_time / $iterations;
echo "array_reverse + array_filter: $avg_time seconds\n";
}
function test_hash_table($array, $iterations) {
$total_time = 0;
for ($i = 0; $i < $iterations; $i++) {
$start_time = microtime(true);
$result = array_values(array_filter($array, function ($value) {
static $hash_table = [];
if (isset($hash_table[$value])) {
return false;
}
$hash_table[$value] = true;
return true;
}));
$end_time = microtime(true);
$total_time += $end_time - $start_time;
}
$avg_time = $total_time / $iterations;
echo "hash table: $avg_time seconds\n";
}
function test_loop($array, $iterations) {
$total_time = 0;
for ($i = 0; $i < $iterations; $i++) {
$start_time = microtime(true);
$result = array_values(array_filter($array, function ($value) use (&$array) {
for ($j = 0; $j < count($array); $j++) {
if ($j == $i) {
continue;
}
if ($value == $array[$j]) {
return false;
}
}
return true;
}));
$end_time = microtime(true);
$total_time += $end_time - $start_time;
}
$avg_time = $total_time / $iterations;
echo "loop: $avg_time seconds\n";
}
test_array_unique($array, $iterations);
test_array_reverse_array_filter($array, $iterations);
test_hash_table($array, $iterations);
test_loop($array, $iterations);结果
使用 100 万个整数的数组,每个函数的平均运行时间如下:
结论
根据测试结果,array_unique() 是去重数组最快的内置函数,而哈希表法是性能最优的自定义函数。循环法虽然容易实现,但效率较低。在处理大型数组时,建议采用 array_unique() 或哈希表法进行去重。
以上就是使用 PHP 内置函数和自定义函数去重数组的性能对比的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号