3

That's about all I need to ask. Checked the PHP manual and saw a user post saying that serialize is 45-90% slower than json_encode (he ran some benchmarks). But how "slow" is slow? I can find a lot of "versus" stuff sprawling around but none of which a beginner like me can relate to.

I just wrote a script that encoded an array in json and another one to decode it. I did same with serialize. Obviuously that won't tell me any significant differences between them.

yretuta
  • 7,963
  • 17
  • 80
  • 151

3 Answers3

3

Do that 10,000 times (each) to (hopefully) get a measurable idea of differences in both memory usage and CPU time.

Mostly the difference won't be significant in terms of performance. Using JSON is useful in two particular circumstances: for returning to a Web browser and for interoperability with other applications (via Web services and other means), particularly those on non-PHP platforms.

cletus
  • 616,129
  • 168
  • 910
  • 942
2

When you only encode/serialize a couple of objects/array, I'd say the difference in speed will not be that important : you genherally won't perceive it.

The difference is that serialize is made especially for PHP ; for instance, information sur as classes are not lost with serialize, and can be retrieved when unserializing.

On the other hand, JSON is not specific to PHP, which means it is a good interchange format -- its primary use being to exchange data between Javascript and PHP.


For instance, consider this piece of code :

class A {
    public $a;
    public function __construct($a) {
        $this->a = $a;
    }
}

$test = new A(10);

Now, let's serialize and unserialize $test :

var_dump(unserialize(serialize($test)));

We get :

object(A)[2]
  public 'a' => int 10

ie, an object, instance of class A.


Now, let's do the same with JSON :

var_dump(json_decode(json_encode($test)));

We now only have an instance of stdClass :

object(stdClass)[2]
  public 'a' => int 10

JSON is nice to exchange data (the 'class A' nformation is important for PHP, but probably doesn't have much sense for another application) ; but has its limitations too.

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
1

If you're transferring data between one application and another, it's usually almost always better to use JSON encoded data rather than PHP serialized data as the later is a format specific to PHP and not as portable as JSON.

Even in a situation where both the server and client are both PHP-based, it behooves you to use a portable format like JSON to allow the creation of new clients in the future without having to change response format from the server.

I haven't done any benchmarking of these two myself, but if you're finding that json encoding is faster than serialization, than all the more reason to use it.

Also, I prefer JSON encoded data as it is easier to read than serialized data and can quickly be thrown into firebug to be visualized.

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89