most performant way to deep copy objects javascript









up vote
0
down vote

favorite












I wanted to deep copy some objects in javascript so that my reducer is pure in redux. Some properties have 1 level of nesting and some have 2 and some have 3 like:



var x = a:9, y:a:b:9, z = a:b:c:9;


So should I use some other technique like:



var newX = ...x, newY = a:...y.a


Should I continue to use the same technique in a loop - write my custom deep copy for 3 level nesting also or should I simply use:



var newZ = JSON.parse(JSON.stringify(z));


to create my deep copy.



What is the fastest way alternative to JSON.parse(JSON.stringify(value))??










share|improve this question



















  • 2




    Possible duplicate of What is the most efficient way to deep clone an object in JavaScript?
    – Vignesh Raja
    Nov 10 at 3:47






  • 1




    If your using it in redux reducer, best way is normalize the state, do not nest object, in redux documentation itself says that link, if you explain your situation with more practical code I can help you.
    – Hafeez Hamza
    Nov 10 at 3:54















up vote
0
down vote

favorite












I wanted to deep copy some objects in javascript so that my reducer is pure in redux. Some properties have 1 level of nesting and some have 2 and some have 3 like:



var x = a:9, y:a:b:9, z = a:b:c:9;


So should I use some other technique like:



var newX = ...x, newY = a:...y.a


Should I continue to use the same technique in a loop - write my custom deep copy for 3 level nesting also or should I simply use:



var newZ = JSON.parse(JSON.stringify(z));


to create my deep copy.



What is the fastest way alternative to JSON.parse(JSON.stringify(value))??










share|improve this question



















  • 2




    Possible duplicate of What is the most efficient way to deep clone an object in JavaScript?
    – Vignesh Raja
    Nov 10 at 3:47






  • 1




    If your using it in redux reducer, best way is normalize the state, do not nest object, in redux documentation itself says that link, if you explain your situation with more practical code I can help you.
    – Hafeez Hamza
    Nov 10 at 3:54













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I wanted to deep copy some objects in javascript so that my reducer is pure in redux. Some properties have 1 level of nesting and some have 2 and some have 3 like:



var x = a:9, y:a:b:9, z = a:b:c:9;


So should I use some other technique like:



var newX = ...x, newY = a:...y.a


Should I continue to use the same technique in a loop - write my custom deep copy for 3 level nesting also or should I simply use:



var newZ = JSON.parse(JSON.stringify(z));


to create my deep copy.



What is the fastest way alternative to JSON.parse(JSON.stringify(value))??










share|improve this question















I wanted to deep copy some objects in javascript so that my reducer is pure in redux. Some properties have 1 level of nesting and some have 2 and some have 3 like:



var x = a:9, y:a:b:9, z = a:b:c:9;


So should I use some other technique like:



var newX = ...x, newY = a:...y.a


Should I continue to use the same technique in a loop - write my custom deep copy for 3 level nesting also or should I simply use:



var newZ = JSON.parse(JSON.stringify(z));


to create my deep copy.



What is the fastest way alternative to JSON.parse(JSON.stringify(value))??







javascript json redux deep-copy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 4:03









Hafeez Hamza

307110




307110










asked Nov 10 at 3:38









Prabhas

434822




434822







  • 2




    Possible duplicate of What is the most efficient way to deep clone an object in JavaScript?
    – Vignesh Raja
    Nov 10 at 3:47






  • 1




    If your using it in redux reducer, best way is normalize the state, do not nest object, in redux documentation itself says that link, if you explain your situation with more practical code I can help you.
    – Hafeez Hamza
    Nov 10 at 3:54













  • 2




    Possible duplicate of What is the most efficient way to deep clone an object in JavaScript?
    – Vignesh Raja
    Nov 10 at 3:47






  • 1




    If your using it in redux reducer, best way is normalize the state, do not nest object, in redux documentation itself says that link, if you explain your situation with more practical code I can help you.
    – Hafeez Hamza
    Nov 10 at 3:54








2




2




Possible duplicate of What is the most efficient way to deep clone an object in JavaScript?
– Vignesh Raja
Nov 10 at 3:47




Possible duplicate of What is the most efficient way to deep clone an object in JavaScript?
– Vignesh Raja
Nov 10 at 3:47




1




1




If your using it in redux reducer, best way is normalize the state, do not nest object, in redux documentation itself says that link, if you explain your situation with more practical code I can help you.
– Hafeez Hamza
Nov 10 at 3:54





If your using it in redux reducer, best way is normalize the state, do not nest object, in redux documentation itself says that link, if you explain your situation with more practical code I can help you.
– Hafeez Hamza
Nov 10 at 3:54













2 Answers
2






active

oldest

votes

















up vote
0
down vote













If you truly want deep cloning, the most performant way by far in my experience is the JSON parse/stringify trick you already mentioned.



Otherwise you'll have to fall back to some sort of recursive cloning strategy. Lodash has a deepClone function for example.



As an alternative to deep cloning, I highly recommend immer, which leverages a concept called structural sharing, in which unchanged parts of the object aren't cloned. This is more performant and uses less memory.






share|improve this answer



























    up vote
    0
    down vote













    I use this function found somewhere on StackOverflow:



    const deepCopy = origin => 
    let cp;
    switch (typeof origin)
    case 'object':
    if (origin === null)
    cp = null;
    else
    switch (toString.call(origin))
    case '[object Array]':
    cp = origin.map(deepCopy);
    break;
    case '[object Date]':
    cp = new Date(origin);
    break;
    case '[object ReqExp]':
    cp = new RegExp(origin);
    break;

    default:
    cp = Object.keys(origin).reduce((prev, key) =>
    prev[key] = deepCopy(origin[key]);
    return prev;
    , );
    break;


    break;

    default:
    cp = origin;


    return cp;






    share|improve this answer




















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      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',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      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%2fstackoverflow.com%2fquestions%2f53235802%2fmost-performant-way-to-deep-copy-objects-javascript%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








      up vote
      0
      down vote













      If you truly want deep cloning, the most performant way by far in my experience is the JSON parse/stringify trick you already mentioned.



      Otherwise you'll have to fall back to some sort of recursive cloning strategy. Lodash has a deepClone function for example.



      As an alternative to deep cloning, I highly recommend immer, which leverages a concept called structural sharing, in which unchanged parts of the object aren't cloned. This is more performant and uses less memory.






      share|improve this answer
























        up vote
        0
        down vote













        If you truly want deep cloning, the most performant way by far in my experience is the JSON parse/stringify trick you already mentioned.



        Otherwise you'll have to fall back to some sort of recursive cloning strategy. Lodash has a deepClone function for example.



        As an alternative to deep cloning, I highly recommend immer, which leverages a concept called structural sharing, in which unchanged parts of the object aren't cloned. This is more performant and uses less memory.






        share|improve this answer






















          up vote
          0
          down vote










          up vote
          0
          down vote









          If you truly want deep cloning, the most performant way by far in my experience is the JSON parse/stringify trick you already mentioned.



          Otherwise you'll have to fall back to some sort of recursive cloning strategy. Lodash has a deepClone function for example.



          As an alternative to deep cloning, I highly recommend immer, which leverages a concept called structural sharing, in which unchanged parts of the object aren't cloned. This is more performant and uses less memory.






          share|improve this answer












          If you truly want deep cloning, the most performant way by far in my experience is the JSON parse/stringify trick you already mentioned.



          Otherwise you'll have to fall back to some sort of recursive cloning strategy. Lodash has a deepClone function for example.



          As an alternative to deep cloning, I highly recommend immer, which leverages a concept called structural sharing, in which unchanged parts of the object aren't cloned. This is more performant and uses less memory.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 4:03









          greim

          6,34052632




          6,34052632






















              up vote
              0
              down vote













              I use this function found somewhere on StackOverflow:



              const deepCopy = origin => 
              let cp;
              switch (typeof origin)
              case 'object':
              if (origin === null)
              cp = null;
              else
              switch (toString.call(origin))
              case '[object Array]':
              cp = origin.map(deepCopy);
              break;
              case '[object Date]':
              cp = new Date(origin);
              break;
              case '[object ReqExp]':
              cp = new RegExp(origin);
              break;

              default:
              cp = Object.keys(origin).reduce((prev, key) =>
              prev[key] = deepCopy(origin[key]);
              return prev;
              , );
              break;


              break;

              default:
              cp = origin;


              return cp;






              share|improve this answer
























                up vote
                0
                down vote













                I use this function found somewhere on StackOverflow:



                const deepCopy = origin => 
                let cp;
                switch (typeof origin)
                case 'object':
                if (origin === null)
                cp = null;
                else
                switch (toString.call(origin))
                case '[object Array]':
                cp = origin.map(deepCopy);
                break;
                case '[object Date]':
                cp = new Date(origin);
                break;
                case '[object ReqExp]':
                cp = new RegExp(origin);
                break;

                default:
                cp = Object.keys(origin).reduce((prev, key) =>
                prev[key] = deepCopy(origin[key]);
                return prev;
                , );
                break;


                break;

                default:
                cp = origin;


                return cp;






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  I use this function found somewhere on StackOverflow:



                  const deepCopy = origin => 
                  let cp;
                  switch (typeof origin)
                  case 'object':
                  if (origin === null)
                  cp = null;
                  else
                  switch (toString.call(origin))
                  case '[object Array]':
                  cp = origin.map(deepCopy);
                  break;
                  case '[object Date]':
                  cp = new Date(origin);
                  break;
                  case '[object ReqExp]':
                  cp = new RegExp(origin);
                  break;

                  default:
                  cp = Object.keys(origin).reduce((prev, key) =>
                  prev[key] = deepCopy(origin[key]);
                  return prev;
                  , );
                  break;


                  break;

                  default:
                  cp = origin;


                  return cp;






                  share|improve this answer












                  I use this function found somewhere on StackOverflow:



                  const deepCopy = origin => 
                  let cp;
                  switch (typeof origin)
                  case 'object':
                  if (origin === null)
                  cp = null;
                  else
                  switch (toString.call(origin))
                  case '[object Array]':
                  cp = origin.map(deepCopy);
                  break;
                  case '[object Date]':
                  cp = new Date(origin);
                  break;
                  case '[object ReqExp]':
                  cp = new RegExp(origin);
                  break;

                  default:
                  cp = Object.keys(origin).reduce((prev, key) =>
                  prev[key] = deepCopy(origin[key]);
                  return prev;
                  , );
                  break;


                  break;

                  default:
                  cp = origin;


                  return cp;







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 at 4:54









                  AlbertS

                  836




                  836



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • 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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2fstackoverflow.com%2fquestions%2f53235802%2fmost-performant-way-to-deep-copy-objects-javascript%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 how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                      Syphilis

                      Darth Vader #20