Optimize list serialization

Instead of calculating the length of the list (iterating it once), then
appending all elements, this new code serializes the list content
whilst traversing it, calculating its length on the go, then prepending
the length value.