Benefits of using sObject.clone versus creating a new recordHow to avoid instantiating object inside a loop?Creating new record with Apex TriggerRestrict on creating new Record by Record TypeDoes deep cloning also create new parent record?Code Coverage to Test Custom Object Public ListExternal id field is not populating when cloning a sobject recordApex: Clone a record, then make the new record the Parent of the old cloned RecordWhat Does My Trigger Do?Create Customize cloning , copying old to new recordVague error message - duplicates value on record with idDetect and mask existing email addresses when creating new record

Work requires me to come in early to start computer but wont let me clock in to get paid for it

Drawing a german abacus as in the books of Adam Ries

Negative Resistance

How to not starve gigantic beasts

Is Electric Central Heating worth it if using Solar Panels?

How much of a wave function must reside inside event horizon for it to be consumed by the black hole?

Suing a Police Officer Instead of the Police Department

Could moose/elk survive in the Amazon forest?

What is the unit of time_lock_delta in LND?

What was Apollo 13's "Little Jolt" after MECO?

Apply a different color ramp to subset of categorized symbols in QGIS?

Creating a chemical industry from a medieval tech level without petroleum

Is it acceptable to use working hours to read general interest books?

What is purpose of DB Browser(dbbrowser.aspx) under admin tool?

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

Why is the underscore command _ useful?

Complex numbers z=-3-4i polar form

How to pronounce 'c++' in Spanish

"Whatever a Russian does, they end up making the Kalashnikov gun"? Are there any similar proverbs in English?

Multiple options vs single option UI

Do I need to watch Ant-Man and the Wasp and Captain Marvel before watching Avengers: Endgame?

Should the Product Owner dictate what info the UI needs to display?

How to keep bees out of canned beverages?

What is this word supposed to be?



Benefits of using sObject.clone versus creating a new record


How to avoid instantiating object inside a loop?Creating new record with Apex TriggerRestrict on creating new Record by Record TypeDoes deep cloning also create new parent record?Code Coverage to Test Custom Object Public ListExternal id field is not populating when cloning a sobject recordApex: Clone a record, then make the new record the Parent of the old cloned RecordWhat Does My Trigger Do?Create Customize cloning , copying old to new recordVague error message - duplicates value on record with idDetect and mask existing email addresses when creating new record






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















Hello I am curious whats the use case of the clone method. Also when its beneficial. Example here I create a lead once then clone it 200 times.



 list<lead> leadlist = new list<lead>();
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');

for(integer i =0; i<200; i++)
lead clone = l.clone(false,false,false,false);
leadlist.add(clone);

insert leadlist;


Is there anybenefit to doing the above clone instead of?



 list<lead> leadlist = new list<lead>();


for(integer i =0; i<200; i++)
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');
leadlist.add(l);


insert leadlist;


I came across this in the Queueable Apex Trailhead In the challenge section where they ask you to add the same primary contact to a bunch of accounts.










share|improve this question

















  • 1





    You use clone to copy record information from existing records, in the trailhead i think they are asking you to use clone since they are asking you to insert the same contact for each account for a specific state which means the information has to be same on contact.Just the billing state changes

    – RedDevil
    Apr 18 at 13:54


















2















Hello I am curious whats the use case of the clone method. Also when its beneficial. Example here I create a lead once then clone it 200 times.



 list<lead> leadlist = new list<lead>();
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');

for(integer i =0; i<200; i++)
lead clone = l.clone(false,false,false,false);
leadlist.add(clone);

insert leadlist;


Is there anybenefit to doing the above clone instead of?



 list<lead> leadlist = new list<lead>();


for(integer i =0; i<200; i++)
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');
leadlist.add(l);


insert leadlist;


I came across this in the Queueable Apex Trailhead In the challenge section where they ask you to add the same primary contact to a bunch of accounts.










share|improve this question

















  • 1





    You use clone to copy record information from existing records, in the trailhead i think they are asking you to use clone since they are asking you to insert the same contact for each account for a specific state which means the information has to be same on contact.Just the billing state changes

    – RedDevil
    Apr 18 at 13:54














2












2








2








Hello I am curious whats the use case of the clone method. Also when its beneficial. Example here I create a lead once then clone it 200 times.



 list<lead> leadlist = new list<lead>();
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');

for(integer i =0; i<200; i++)
lead clone = l.clone(false,false,false,false);
leadlist.add(clone);

insert leadlist;


Is there anybenefit to doing the above clone instead of?



 list<lead> leadlist = new list<lead>();


for(integer i =0; i<200; i++)
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');
leadlist.add(l);


insert leadlist;


I came across this in the Queueable Apex Trailhead In the challenge section where they ask you to add the same primary contact to a bunch of accounts.










share|improve this question














Hello I am curious whats the use case of the clone method. Also when its beneficial. Example here I create a lead once then clone it 200 times.



 list<lead> leadlist = new list<lead>();
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');

for(integer i =0; i<200; i++)
lead clone = l.clone(false,false,false,false);
leadlist.add(clone);

insert leadlist;


Is there anybenefit to doing the above clone instead of?



 list<lead> leadlist = new list<lead>();


for(integer i =0; i<200; i++)
lead l = new lead(firstname = 'merp', lastname ='derp', company='CNN');
leadlist.add(l);


insert leadlist;


I came across this in the Queueable Apex Trailhead In the challenge section where they ask you to add the same primary contact to a bunch of accounts.







apex sobject clone






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 18 at 13:49









Ryan SherryRyan Sherry

676




676







  • 1





    You use clone to copy record information from existing records, in the trailhead i think they are asking you to use clone since they are asking you to insert the same contact for each account for a specific state which means the information has to be same on contact.Just the billing state changes

    – RedDevil
    Apr 18 at 13:54













  • 1





    You use clone to copy record information from existing records, in the trailhead i think they are asking you to use clone since they are asking you to insert the same contact for each account for a specific state which means the information has to be same on contact.Just the billing state changes

    – RedDevil
    Apr 18 at 13:54








1




1





You use clone to copy record information from existing records, in the trailhead i think they are asking you to use clone since they are asking you to insert the same contact for each account for a specific state which means the information has to be same on contact.Just the billing state changes

– RedDevil
Apr 18 at 13:54






You use clone to copy record information from existing records, in the trailhead i think they are asking you to use clone since they are asking you to insert the same contact for each account for a specific state which means the information has to be same on contact.Just the billing state changes

– RedDevil
Apr 18 at 13:54











2 Answers
2






active

oldest

votes


















5














There was a question a while back that can provide some context here: How to avoid instantiating object inside a loop?



To summarize:



  • Cloning is very fast

  • Using the SObject constructor to set name-value pairs is also very fast, and faster than cloning if you need to change even a single field on a cloned record (e.g. newRec = record.clone(); newRec.Field = value;)

  • Both approaches will "break the reference" so that you have multiple in-memory instances of your target record (as opposed to a single in-memory instance that gets shared, which means changes to any of the "referenced" copies affects all of the referenced copies)

  • But most importantly, the performance difference between the two is negligible. Don't waste your time on micro-optimizations like this

Depending on how many fields the object you're trying to duplicate has (and how many fields you need to change between instances), cloning can result in less typing.



Honestly, there's not much benefit to one over the other. The greatest benefit here will probably come from choosing the right tool for the job (e.g. clone() is good when you need to do some processing or make changes to a record but still need the original values to remain intact for something else) and being consistent across your code base.






share|improve this answer






























    1














    If you create a record multiple times without cloning then all the record relationships are disjoint. So, changing an object will not change other objects.



    If you clone like the above way then that is known as Deep cloning. So, All fields on the SObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned SObject, the original SObject is not affected.



    Whereas for Shallow cloning, if you make changes to a relationship field on the cloned SObject, the corresponding field on the original SObject is also affected, and vice versa



    So, cloning is faster than creating new records without cloning. Moreover Shallow cloning is faster than deep cloning.




    Use Case of cloning could be: customer has purchased a property and business wants to create payment schedule, EMI information for a number of months.




    In this scenario, most of the information will be same only month for Payment will be different. So, better to use clone functionality to create records.






    share|improve this answer























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "459"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f258331%2fbenefits-of-using-sobject-clone-versus-creating-a-new-record%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5














      There was a question a while back that can provide some context here: How to avoid instantiating object inside a loop?



      To summarize:



      • Cloning is very fast

      • Using the SObject constructor to set name-value pairs is also very fast, and faster than cloning if you need to change even a single field on a cloned record (e.g. newRec = record.clone(); newRec.Field = value;)

      • Both approaches will "break the reference" so that you have multiple in-memory instances of your target record (as opposed to a single in-memory instance that gets shared, which means changes to any of the "referenced" copies affects all of the referenced copies)

      • But most importantly, the performance difference between the two is negligible. Don't waste your time on micro-optimizations like this

      Depending on how many fields the object you're trying to duplicate has (and how many fields you need to change between instances), cloning can result in less typing.



      Honestly, there's not much benefit to one over the other. The greatest benefit here will probably come from choosing the right tool for the job (e.g. clone() is good when you need to do some processing or make changes to a record but still need the original values to remain intact for something else) and being consistent across your code base.






      share|improve this answer



























        5














        There was a question a while back that can provide some context here: How to avoid instantiating object inside a loop?



        To summarize:



        • Cloning is very fast

        • Using the SObject constructor to set name-value pairs is also very fast, and faster than cloning if you need to change even a single field on a cloned record (e.g. newRec = record.clone(); newRec.Field = value;)

        • Both approaches will "break the reference" so that you have multiple in-memory instances of your target record (as opposed to a single in-memory instance that gets shared, which means changes to any of the "referenced" copies affects all of the referenced copies)

        • But most importantly, the performance difference between the two is negligible. Don't waste your time on micro-optimizations like this

        Depending on how many fields the object you're trying to duplicate has (and how many fields you need to change between instances), cloning can result in less typing.



        Honestly, there's not much benefit to one over the other. The greatest benefit here will probably come from choosing the right tool for the job (e.g. clone() is good when you need to do some processing or make changes to a record but still need the original values to remain intact for something else) and being consistent across your code base.






        share|improve this answer

























          5












          5








          5







          There was a question a while back that can provide some context here: How to avoid instantiating object inside a loop?



          To summarize:



          • Cloning is very fast

          • Using the SObject constructor to set name-value pairs is also very fast, and faster than cloning if you need to change even a single field on a cloned record (e.g. newRec = record.clone(); newRec.Field = value;)

          • Both approaches will "break the reference" so that you have multiple in-memory instances of your target record (as opposed to a single in-memory instance that gets shared, which means changes to any of the "referenced" copies affects all of the referenced copies)

          • But most importantly, the performance difference between the two is negligible. Don't waste your time on micro-optimizations like this

          Depending on how many fields the object you're trying to duplicate has (and how many fields you need to change between instances), cloning can result in less typing.



          Honestly, there's not much benefit to one over the other. The greatest benefit here will probably come from choosing the right tool for the job (e.g. clone() is good when you need to do some processing or make changes to a record but still need the original values to remain intact for something else) and being consistent across your code base.






          share|improve this answer













          There was a question a while back that can provide some context here: How to avoid instantiating object inside a loop?



          To summarize:



          • Cloning is very fast

          • Using the SObject constructor to set name-value pairs is also very fast, and faster than cloning if you need to change even a single field on a cloned record (e.g. newRec = record.clone(); newRec.Field = value;)

          • Both approaches will "break the reference" so that you have multiple in-memory instances of your target record (as opposed to a single in-memory instance that gets shared, which means changes to any of the "referenced" copies affects all of the referenced copies)

          • But most importantly, the performance difference between the two is negligible. Don't waste your time on micro-optimizations like this

          Depending on how many fields the object you're trying to duplicate has (and how many fields you need to change between instances), cloning can result in less typing.



          Honestly, there's not much benefit to one over the other. The greatest benefit here will probably come from choosing the right tool for the job (e.g. clone() is good when you need to do some processing or make changes to a record but still need the original values to remain intact for something else) and being consistent across your code base.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 18 at 14:21









          Derek FDerek F

          21.1k52353




          21.1k52353























              1














              If you create a record multiple times without cloning then all the record relationships are disjoint. So, changing an object will not change other objects.



              If you clone like the above way then that is known as Deep cloning. So, All fields on the SObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned SObject, the original SObject is not affected.



              Whereas for Shallow cloning, if you make changes to a relationship field on the cloned SObject, the corresponding field on the original SObject is also affected, and vice versa



              So, cloning is faster than creating new records without cloning. Moreover Shallow cloning is faster than deep cloning.




              Use Case of cloning could be: customer has purchased a property and business wants to create payment schedule, EMI information for a number of months.




              In this scenario, most of the information will be same only month for Payment will be different. So, better to use clone functionality to create records.






              share|improve this answer



























                1














                If you create a record multiple times without cloning then all the record relationships are disjoint. So, changing an object will not change other objects.



                If you clone like the above way then that is known as Deep cloning. So, All fields on the SObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned SObject, the original SObject is not affected.



                Whereas for Shallow cloning, if you make changes to a relationship field on the cloned SObject, the corresponding field on the original SObject is also affected, and vice versa



                So, cloning is faster than creating new records without cloning. Moreover Shallow cloning is faster than deep cloning.




                Use Case of cloning could be: customer has purchased a property and business wants to create payment schedule, EMI information for a number of months.




                In this scenario, most of the information will be same only month for Payment will be different. So, better to use clone functionality to create records.






                share|improve this answer

























                  1












                  1








                  1







                  If you create a record multiple times without cloning then all the record relationships are disjoint. So, changing an object will not change other objects.



                  If you clone like the above way then that is known as Deep cloning. So, All fields on the SObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned SObject, the original SObject is not affected.



                  Whereas for Shallow cloning, if you make changes to a relationship field on the cloned SObject, the corresponding field on the original SObject is also affected, and vice versa



                  So, cloning is faster than creating new records without cloning. Moreover Shallow cloning is faster than deep cloning.




                  Use Case of cloning could be: customer has purchased a property and business wants to create payment schedule, EMI information for a number of months.




                  In this scenario, most of the information will be same only month for Payment will be different. So, better to use clone functionality to create records.






                  share|improve this answer













                  If you create a record multiple times without cloning then all the record relationships are disjoint. So, changing an object will not change other objects.



                  If you clone like the above way then that is known as Deep cloning. So, All fields on the SObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned SObject, the original SObject is not affected.



                  Whereas for Shallow cloning, if you make changes to a relationship field on the cloned SObject, the corresponding field on the original SObject is also affected, and vice versa



                  So, cloning is faster than creating new records without cloning. Moreover Shallow cloning is faster than deep cloning.




                  Use Case of cloning could be: customer has purchased a property and business wants to create payment schedule, EMI information for a number of months.




                  In this scenario, most of the information will be same only month for Payment will be different. So, better to use clone functionality to create records.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 18 at 14:37









                  Santanu BoralSantanu Boral

                  31.5k52456




                  31.5k52456



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Salesforce Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f258331%2fbenefits-of-using-sobject-clone-versus-creating-a-new-record%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to write a 12-bar blues melodyI-IV-V blues progressionHow to play the bridges in a standard blues progressionHow does Gdim7 fit in C# minor?question on a certain chord progressionMusicology of Melody12 bar blues, spread rhythm: alternative to 6th chord to avoid finger stretchChord progressions/ Root key/ MelodiesHow to put chords (POP-EDM) under a given lead vocal melody (starting from a good knowledge in music theory)Are there “rules” for improvising with the minor pentatonic scale over 12-bar shuffle?Confusion about blues scale and chords

                      What if the end-user didn't have the required library?What is setup.py?What is a clean, pythonic way to have multiple constructors in Python?What does Ruby have that Python doesn't, and vice versa?What is the reason for having '//' in Python?How do I create a namespace package in Python?How to package shared objects that python modules depend on?setuptools vs. distutils: why is distutils still a thing?Navigation in Windows 10 vs code not going to virtualenv library when the same library is installed at user levelPython create package for local usePackaging a project that uses multiple python versionsWhy is permission denied on pip install except for when “--user” is included at end of command?

                      Esgonzo ibérico Índice Descrición Distribución Hábitat Ameazas Notas Véxase tamén "Acerca dos nomes dos anfibios e réptiles galegos""Chalcides bedriagai"Chalcides bedriagai en Carrascal, L. M. Salvador, A. (Eds). Enciclopedia virtual de los vertebrados españoles. Museo Nacional de Ciencias Naturales, Madrid. España.Fotos