note 84959 added to function.array-push
| From: | willdemaine at gmail dot com | Date: | Thu, 07 Aug 2008 14:00:09 +0000 |
| Subject: | note 84959 added to function.array-push | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-143274@lists.php.net to get a copy of this message | ||
If you're adding multiple values to an array in a loop, it's faster to use array_push than
repeated [] = statements that I see all the time:
<?php
class timer
{
private $start;
private $end;
public function timer()
{
$this->start = microtime(true);
}
public function Finish()
{
$this->end = microtime(true);
}
private function GetStart()
{
if (isset($this->start))
return $this->start;
else
return false;
}
private function GetEnd()
{
if (isset($this->end))
return $this->end;
else
return false;
}
public function GetDiff()
{
return $this->GetEnd() - $this->GetStart();
}
public function Reset()
{
$this->start = microtime(true);
}
}
echo "Adding 100k elements to array with []\n\n";
$ta = array();
$test = new Timer();
for ($i = 0; $i < 100000; $i++)
{
$ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();
echo "\n\nAdding 100k elements to array with array_push\n\n";
$test->Reset();
for ($i = 0; $i < 100000; $i++)
{
array_push($ta,$i);
}
$test->Finish();
echo $test->GetDiff();
echo "\n\nAdding 100k elements to array with [] 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
$ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();
echo "\n\nAdding 100k elements to array with array_push 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
array_push($ta,$i,$i,$i,$i,$i,$i,$i,$i,$i,$i);
}
$test->Finish();
echo $test->GetDiff();
?>
Output
$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html
Adding 100k elements to array with []
0.044686794281006
Adding 100k elements to array with array_push
0.072616100311279
Adding 100k elements to array with [] 10 per iteration
0.034690141677856
Adding 100k elements to array with array_push 10 per iteration
0.023932933807373
----
Server IP: 92.48.74.199
Probable Submitter: 79.170.40.31
----
Manual Page -- http://www.php.net/manual/en/function.array-push.php
Edit -- https://master.php.net/note/edit/84959
Del: integrated -- https://master.php.net/note/delete/84959/integrated
Del: useless -- https://master.php.net/note/delete/84959/useless
Del: bad code -- https://master.php.net/note/delete/84959/bad+code
Del: spam -- https://master.php.net/note/delete/84959/spam
Del: non-english -- https://master.php.net/note/delete/84959/non-english
Del: in docs -- https://master.php.net/note/delete/84959/in+docs
Del: other reasons-- https://master.php.net/note/delete/84959
Reject -- https://master.php.net/note/reject/84959
Search -- https://master.php.net/manage/user-notes.php