![](/img/trans.png)
[英]Silex - What's the fastest way to serialize a database resultset in JSON?
[英]What is the fastest way to turn an object's public properties into JSON
我的用例:
fetchObject('ClassName')
獲取行現在我有一個包含 500 個填充對象的數組,我想把它變成 JSON afap
目前我正在使用以下方法:
function get_object_public_vars($object) {
return get_object_vars($object);
}
class Model implements \JsonSerializable {
public $property1;
public $property2;
private $property3;
public function jsonSerialize() {
return get_object_public_vars($this);
}
}
然后我做
// $dbStatement is a PDOStatement with a MySQL select query prepared
$a500objects = $dbStatement->fetchAll(\PDO::FETCH_CLASS, 'Model');
echo json_encode($a500objects);
現在我做了一些測試,如果我改為$dbStatement->fetchAll();
沒有class_name
參數。 代碼運行得更快,並且在選擇更多行時會擴展。
但是我需要“模型”對象來實現一些應用程序邏輯。 運行get_object_vars()
500x 似乎需要時間。 (即使使用 OpCache)
有誰知道將 class 'Model' 對象解析為 JSON 的更快方法?
你試過這個嗎?
public function jsonSerialize()
{
return
[
'property1' => $this->property1,
'property2' => $this->property2,
'property3' => $this->property3,
];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.