LoginSignup
35
32

More than 5 years have passed since last update.

PHPでオブジェクトを連想配列に変換するのはarrayキャストが速い

Posted at

PHPでオブジェクトを連想配列に変換させるのは

$array = json_decode(json_encode($object), true);

こんなふうにjson_decode()json_encode()を駆使してたのですが、arrayでキャストする方法を(今更ながら)知りました。

で、ついでだからjson関数で変換する方法とarrayキャストする方法で速度比較を行ってみました。

cast.php
<?php

class hoge {
    public $prop0 = 0;
    public $prop1 = 'value1';
}

for ($i = 0; $i < 1000000; $i++) {
    $object = new hoge();
    $array = (array)$object;
    $value = $array['prop0'];
}
json.php
<?php

class hoge {
    public $prop0 = 0;
    public $prop1 = 'value1';
}

for ($i = 0; $i < 1000000; $i++) {
    $object = new hoge();
    $array = json_decode(json_encode($object), true);
    $value = $array['prop0'];
}

このようにhogeクラスをnewしたあとにarrayでキャストするcast.php、json_decode()json_encode()で変換するjson.phpを用意して、timeコマンドで実行時間を計ってみました。以下結果。

$ time php cast.php
php cast.php  0.57s user 0.01s system 99% cpu 0.583 total
$ time php json.php
php json.php  2.72s user 0.02s system 99% cpu 2.740 total

当たり前ですけれど、関数を2つ使うjson.phpのほうが圧倒的に遅いですね。

35
32
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
32