Fast Creation Of stdClass Objects¶
<?php
// fastest
$final = (object) ['a' => 1, 'b' => 2];
// 2nd fastest
$array = [];
$array['a'] = 1;
$array['b'] = 2;
$final = (object) $array;
//slow
$final = new stdClass();
$final->a = 1;
$final->b = 2;
//slowest
class myStdClass extends stdClass {
$function __construct($a, $b) {
$this->a = $a;
$this->b = $b;
}
}
$final = new mystdclass(1, 2);
The fastest way to create a stdClass object is to create an array, and then cast it to stdClass with the (array) cast operator. It is still faster even if the array is build piece-meal: two times slower.
Setting directly properties on the stdClass object is then about three times slower, and creating a class extension with an adapted __construct method is then four times slower.
In the end, this is a micro optimisation.
See Also¶
PHP Features¶
Last updated: 14 July 2026