Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I Use Angular.copy() or _.clone()?

I'm working on a project that has both Angular and Underscore as a dependency.

When I need to create a copy of an object, depending on my mood at the time, I might use angular.copy() or _.clone()

It occurs to me that one of these methods is probably more fast/reliable/robust than the other.

Are there any known issue with either of these functions that make it better or worse to use than the other, assuming both libraries are already included?

like image 462
Code Whisperer Avatar asked Oct 16 '14 18:10

Code Whisperer


People also ask

What's alternative to Angular copy in Angular?

The alternative for deep copying objects having nested objects inside is by using lodash's cloneDeep method. For Angular, you can do it like this: Install lodash with yarn add lodash or npm install lodash .

What is the use of Angular copy?

copy when assigning value of object or array to another variable and that object value should not be changed. Without deep copy or using angular. copy, changing value of property or adding any new property update all object referencing that same object.

What is the difference between creating an array using assignment and copy () function?

copy() performs a deep copy (cf. "clone") of the argument - essentially creating a new object - whereas using the assignment operator = just assigns reference's.

What is shallow copy and deep copy in Angular?

shallow copying. A deep copy means that all of the values of the new variable are copied and disconnected from the original variable. A shallow copy means that certain (sub-)values are still connected to the original variable.


1 Answers

Regarding your question: angular.copy and _.clone are different. It's not a question of which is better, it is about what you need as @Kevin B stated in the comments.

angular.extend() on the other hand, is a shallow copy akin to _.clone

Angular.copy vs Angular.extend

Performance wise, i'm not sure which is better, but for opinions sake, i'm opposed to including libraries into the global scope (underscore) with any angular app, as usually these things are written as angular modules. angular.copy/angular.extend would win in this case.

Shallow/Deep Copy:

Its very simple that if the object has only primitive fields, then obviously you will go for shallow copy but if the object has references to other objects, then based on the requiement, shallow copy or deep copy should be chosen. What I mean here is, if the references are not modified anytime, then there is no point in going for deep copy. You can just opt shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement.

Source

like image 193
dannypaz Avatar answered Sep 29 '22 07:09

dannypaz