我有一个包含约30个设置的对象.
1页可以包含10个对象,每个对象最多具有15个设置.
为了初始化对象,我从数据库中为每个对象获取一个关联数组.
我想知道什么是最好的表现?我目前有(示例):
$object = new element_class();
$array = <query from database>
//Reinitialize object to remove any set values of object properties to null
foreach($object as $key=>$value)
{
$object->$key = null;
}
//Switch of array to set the values in the array in the object properties
foreach($array as $key=>$value)
{
switch($key)
{
case 'a':
$this->property_a = $value;
break;
case 'b':
$this->property_b = $value;
break;
case 'c':
$this->property_c = $value;
break;
case 'd':
$this->property_d = $value;
break;
etc....
}
}
//Default section to set necessary properties if not in database array
foreach($object as $key=>$value)
{
if($value == null)
{
switch ($key)
{
case 'property_a':
$object->$key = <any value here>;
break;
case 'property_b':
$object->$key = <any value here>;
break;
case 'property_c':
$object->$key = <any value here>;
break;
etc.....
}
}
}
这三个步骤是否有更快的方法?
任何性能的提高都是值得欢迎的,特别是因为其中有很多…
解决方法:
这个
$object = new element_class();
//Reinitialize object to remove any set values of object properties to null
foreach($object as $key=>$value)
$object->$key = null;
可以被替换为
$object = new element_class();
假设您定义了公共$fields,默认情况下将其初始化为null.
这个
$array = <query from database>
//Switch of array to set the values in the array in the object properties
foreach($array as $key=>$value)
{
switch($key)
{
case 'a':
$this->property_a = $value;
break;
case 'b':
$this->property_b = $value;
break;
case 'c':
$this->property_c = $value;
break;
case 'd':
$this->property_d = $value;
break;
etc....
}
}
可以替换为
$settings = (object) $array;
它将设置与$this分开,因此您可以轻松保存它们.
这个
//Default section to set necessary properties if not in database array
foreach($object as $key=>$value)
if($value == null)
switch ($key)
{
case 'property_a':
$object->$key = <any value here>;
break;
case 'property_b':
$object->$key = <any value here>;
break;
case 'property_c':
$object->$key = <any value here>;
break;
etc.....
}
应该由element_class()构造函数完成,如下所示:
class element_class {
public $a = <any value here>;
public $b = <any value here>;
....
}
然后,您消除了空循环(或者改为将其替换为设置默认值),而您要做的就是用从< query>获取的值覆盖它们.
$defaults = [
'a' => <any value here>,
'b' => <any value here>,
...
];
$array = <query>;
$settings = (object) array_merge( $defaults, $array );
我不知道它是否更快,但是更容易维护.
如果根本不考虑速度,则应该与SQL查询的数量有关.您说您有“ 10”个对象,每个对象约有“ 15”行.通过执行1个查询返回大约150个对象,您将获得更大的速度提升.