Steven Vachon

Benchmark: PHP array_splice vs. unset & array_values

0 comments

If you’re wondering which of these two popular techniques for removing array indexes is fastest, this should be of some help.

Function Time Comparison
unset() & array_values() 1.645 seconds (10.3% faster)
array_splice() 1.834 seconds

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
 
function getmicrotime()
{
	list($usec, $sec) = explode(' ',microtime());
	return ((float)$usec + (float)$sec);
}
 
$time_start = getmicrotime();
for ($i=0; $i<1000000; $i++)
{
	$test_array = array(0,1,2,3,4,5);
	array_splice($test_array, 3, 1);
}
echo 'array_splice() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
$time_start = getmicrotime();
for ($i=0; $i<1000000; $i++)
{
	$test_array = array(0,1,2,3,4,5);
	unset($test_array[3]);
	$test_array = array_values($test_array);
}
echo 'unset() & array_values() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
?>


Comments

Top

Leave a Reply

Comments welcome! Name & email required; email always kept private. Please use basic markup. Wrap code with <code> tags.