meteorBuzz
meteorBuzz

Reputation: 3200

What happens to an array after a copy has been created?

What happens to the original array when you use a function in underscore for example, and it returns 'a copy of the array'?

Does it stay in memory until the browsers cache is cleared (assuming there is no permanent Session)

Is there any good javascript "best practice" methods to follow when a copy is created. I would like to understand if the copy is referencing the original, in other words, is there a need to keep the original?

Using underscore _.without for the sake of context:

without_.without(array, *values) 

Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

Upvotes: 1

Views: 44

Answers (1)

musically_ut
musically_ut

Reputation: 34288

Javascript, unlike C/C++, does memory management for the programmer. Hence, all variables which cannot be reached by the program in any way, (e.g. the array passed as an argument to _.without) will eventually be collected by the Garbage collector. The exact moment when the collection happens will depend on the underlying implementation of the Javascript Engine, e.g. V8 (Chrome) will probably do it at a differently than SpiderMonkey (Firefox).

For more details, see the MDN article about memory management.


As for whether this is a good idea or not depends on how important performance is for your app. For most apps, it doesn't make much difference. Personally, I prefer creating copies of objects over destructive updates as a way to get immutability and thereby, to make it easier for me to reason about my programs.

However, if you are writing a library which performs computationally expensive tasks, then avoiding copies and updating objects in memory might give you better performance.

Let benchmarks (not microbenchmark, though) make the decisions in the end.

Upvotes: 2

Related Questions