Tag Archives: DeepClone

Difference Between Clone and DeepClone in Apex in Salesforce

Clone Deep Clone
Generally clone the list of object and keep the reference. Generally it clone the list of object but don’t hold any reference.
A Clone doesn’t keep the Ids. A Deep Clone keeps the Id.
Supports primitive data type. Doesn’t support primitive datatype.
Parameters are not applicable. Parameter are applicable.

Here is a an example to understand difference between Clone and DeepClone:
I am creating a New Account with some fields.

Account acc = new account(Name = 'Salesforce', Billingcity = 'San Francisco', Type = 'Customer - Direct', Phone = '9999999999');
insert acc;

This creates a record in the Account as shown below:

Now, I am cloning it and inserting again.

Account acc = new account(Name = 'Salesforce', Billingcity = 'San Francisco', Type = 'Customer - Direct', Phone = '9999999999');
insert acc;

//Cloning the above Account Record acc
Account accCloneCopy  = acc.clone(false, false, false, false);
insert accCloneCopy;

It creates a new copy of the record with same values, since it keeps the reference, new record ID is generated for cloned record.

Now, when I try to deepclone the record: (Deepclone is done by keeping true in the parameters) like,
clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber)

Account acc = new account(Name = 'Salesforce', Billingcity = 'San Francisco', Type = 'Customer - Direct', Phone = '9999999999');
insert acc;

//Deep cloning the above record
Account accDeepCloneCopy  = acc.clone(true, true, false, false);
insert accDeepCloneCopy;

It shows an error, because the Id is also considered and cannot insert the deppcloned record: