Object overhead vs. arrays
| From: | Christoph Boget | Date: | Thu, 07 Aug 2008 13:21:49 +0000 |
| Subject: | Object overhead vs. arrays | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-277811@lists.php.net to get a copy of this message | ||
I knew that there would be some overhead when working with objects vs
working with arrays, but I didn't expect this much. Is there some
optimization that I could do to improve the performance any? While
the script below is just a benchmark test script, it approximates
functionality that I'm going to need to implement. Ultimately, I need
to iterate through a large amount of data and am wondering if perhaps
I should encapsulate the data in objects (which closer represents the
underlying data) or if I should encapsulate it in arrays. Based on
what I'm seeing in this benchmark script, it seems like it should be
the latter...
Advice and/or input would be much appreciated!
thnx,
Christoph
<?php
class TestObj
{
private $sVar1;
private $sVar2;
private $sVar3;
private $aVar4;
public function __construct()
{
}
public function setVar1( $sValue )
{
$this->sVar1 = $sValue;
}
public function setVar2( $sValue )
{
$this->sVar2 = $sValue;
}
public function setVar3( $sValue )
{
$this->sVar3 = $sValue;
}
public function setVar4( $aValue )
{
$this->aVar4 = $aValue;
}
}
$iMaxIterations = rand( 1, 123456 );
$iMaxElements = rand( 1, 10 );
$aMasterArraysArray = array();
$aMasterObjsArray = array();
$aWorkingTmp = array();
for( $i = 0; $i <= $iMaxElements; $i++ )
{
$aWorkingTmp[] = 'Testing';
}
$iStartTime = microtime( TRUE );
for( $i = 0; $i < $iMaxIterations; $i++ )
{
$aTmp = array();
$aTmp['var1'] = rand();
$aTmp['var2'] = rand();
$aTmp['var3'] = rand();
$aTmp['var4'] = $aWorkingTmp;
$aMasterArraysArray[] = $aTmp;
}
$iEndTime = microtime( TRUE );
$iArrayTotalTime = ( $iEndTime - $iStartTime );
echo $iArrayTotalTime . ' seconds elapsed for [' . $iMaxIterations .
'] iterations for ARRAY.<br>';
$iStartTime = microtime( TRUE );
for( $i = 0; $i < $iMaxIterations; $i++ )
{
$oTmp = new TestObj();
$oTmp->setVar1( rand());
$oTmp->setVar2( rand());
$oTmp->setVar3( rand());
$oTmp->setVar4( $aWorkingTmp );
$aMasterObjsArray[] = $oTmp;
}
$iEndTime = microtime( TRUE );
$iObjectTotalTime = ( $iEndTime - $iStartTime );
echo $iObjectTotalTime . ' seconds elapsed for [' . $iMaxIterations
. '] iterations for OBJECTS.<br><br>';
if( $iArrayTotalTime > $iObjectTotalTime )
{
echo 'Arrays took [' . ( $iArrayTotalTime - $iObjectTotalTime ) .
'] seconds longer,
a factor of [' . ( $iArrayTotalTime / $iObjectTotalTime ) . ']<br>';
}
else
{
echo 'Objects took [' . ( $iObjectTotalTime - $iArrayTotalTime ) .
'] seconds longer,
a factor of [' . ( $iObjectTotalTime / $iArrayTotalTime ) . ']<br>';
}
?>