A deep copy is effectively a clone of an object or array. Unlike a shallow copy, a deep copy is not linked to the original object in any way. All properties and sub-objects are recreated with the same values.

Here’s a simple utility class I created, with a single clone() method that performs a deep copy:

package
{
    import flash.utils.ByteArray;

    public class DeepCopyUtil
    {
        public static function clone (source : Object) : *
        {
            var array : ByteArray = new ByteArray ();

            array.writeObject (source);
            array.position = 0;

            return array.readObject ();
        }

    }
}


Where would something like this be useful?

Let’s say you have a template for an array of data. When you create a new array, you want to start with the template as a default, but you don’t want to actually reference the template array. So you make a deep copy instead:

var templateArray : Array = [
    {name:"John Smith", age:28, email:"john@smithy.com"},
    {name:"Jane Smith", age:26, email:"jane@smithy.com"},
    {name:"The Doctor", age:900, email:"doc@tardis.org"}
];

var newArray : Array = DeepCopyUtil.clone (templateArray);


Using this method, any changes made to newArray will not affect templateArray.