Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - *fast* serialize/unserialize?

I have a PHP script that builds a binary search tree over a rather large CSV file (5MB+). This is nice and all, but it takes about 3 seconds to read/parse/index the file.

Now I thought I could use serialize() and unserialize() to quicken the process. When the CSV file has not changed in the meantime, there is no point in parsing it again.

To my horror I find that calling serialize() on my index object takes 5 seconds and produces a huge (19MB) text file, whereas unserialize() takes unbearable 27 seconds to read it back. Improvements look a bit different. ;-)

So - is there a faster mechanism to store/restore large object graphs to/from disk in PHP?

(To clarify: I'm looking for something that takes significantly less than the aforementioned 3 seconds to do the de-serialization job.)

like image 376
Tomalak Avatar asked Mar 30 '10 13:03

Tomalak


People also ask

What is unserialize PHP?

The unserialize() function converts serialized data back into actual data.

How can I serialize data in PHP?

To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.

What is serialization in PHP with example?

Definition and Usage The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.

What is unserialize in laravel?

unserialize() takes a single serialized variable and converts it back into a PHP value.


2 Answers

var_export should be lots faster as PHP won't have to process the string at all:

// export the process CSV to export.php
$php_array = read_parse_and_index_csv($csv); // takes 3 seconds
$export = var_export($php_array, true);
file_put_contents('export.php', '<?php $php_array = ' . $export . '; ?>');

Then include export.php when you need it:

include 'export.php';

Depending on your web server set up, you may have to chmod export.php to make it executable first.

like image 147
dave1010 Avatar answered Oct 30 '22 01:10

dave1010


Try igbinary...did wonders for me:

http://pecl.php.net/package/igbinary

like image 36
Asad Hasan Avatar answered Oct 30 '22 02:10

Asad Hasan