Skip to content

Instantly share code, notes, and snippets.

@thiagophx
Created September 28, 2011 13:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagophx/1247878 to your computer and use it in GitHub Desktop.
Save thiagophx/1247878 to your computer and use it in GitHub Desktop.
Object creation in PHP, which approach is faster? new, clone or unserialize???
<?php
function leSerialize()
{
for ($i = 0; $i < 1000; $i++)
unserialize('O:8:"stdClass":0:{}');
}
function leNew()
{
for ($i = 0; $i < 1000; $i++)
new stdClass();
}
function leClone()
{
$a = new stdClass();
for ($i = 0; $i < 1000; $i++)
clone $a;
}
leSerialize();
leNew();
leClone();
<?php
function leSerialize()
{
for ($i = 0; $i < 1000; $i++)
unserialize('O:8:"stdClass":0:{}');
}
function leNew()
{
for ($i = 0; $i < 1000; $i++)
new stdClass();
}
function leClone()
{
$a = new stdClass();
for ($i = 0; $i < 1000; $i++)
clone $a;
}
function leJson()
{
$json = '{}';
for ($i = 0; $i < 1000; $i++)
json_decode($json);
}
function leReflection()
{
$class = new ReflectionClass('stdClass');
for ($i = 0; $i < 1000; $i++)
$class->newInstance();
}
leSerialize();
leNew();
leClone();
leJson();
leReflection();
@thiagophx
Copy link
Author

http://p.twimg.com/AablsOcCQAAnjnv.png:large Image of the benchmark results

@kinncj
Copy link

kinncj commented Sep 28, 2011

i'm burn.
Cool, our job discuss... maybe we can use reflection, json_decode and others too

@thiagophx
Copy link
Author

@alganet
Copy link

alganet commented Sep 29, 2011

You should run the tests in separate processes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment