"Andrew" <an****@nowhere nohow.com> wrote in message
news:Wi******** *********@newsr ead1.news.pas.e arthlink.net...
Some have suggested that using serialize()
and unserialize is faster than reading/writing
an array to disk as a simple text file using
$array = file('numbers.t xt');
Can anyone justify this?
It seems to me that there is some overhead
associated with calling unserialize().
Is this actually faster than using file()?
I was the one who said it so I'll explain my rationale. Serialize is
marginally faster than file because the format is optimized for easy parse.
Take the following array:
$a = array("This is a test", "Hello world");
Run it through serialize() and you get:
a:2:{i:0;s:14:" This is a test";i:1;s:11: "Hello world";}
How look at this carefully. "a:2" indicates an array with two elements. So
now the start PHP knows how large the array is going to be, and can thus
allocate enough memory from the getgo to hold the entire array. In case of
file() the function does not know how many lines there will be, so it has to
reallocate memory continually as more lines are read.
Now look at "s:14". That stands for a string with a length of 14. Again, PHP
knows how long the string is going to be before it reads the data, so it can
allocate a buffer of just the right size. Moreover, since it knows so many
characters the string takes up in the input data, it can jump ahead to the
next variable without having to examine each characters in the string. In
contrast file() needs to look at every character to know where a newline
starts.
Using serialize also means you don't have to deal with the carriage returns
at the end of every element.