As per my understanding, one of the characteristics of functional programming is the way we deal with mutable objects.
Ex:
var notFunctionalFilter = function(objectArray) {
for (var i=0; i< objectArray.length; i++) {
if (objectArray[i].active) {
objectArray.splice(i, 1);
i --;
}
}
return objectArray;
};
var functionalFilter = function(objectArray) {
var filtered = [];
for (var i=0; i< objectArray.length; i++) {
if (objectArray[i].active) {
filtered.push(objectArray[i]);
}
}
return filtered;
};
I tend to write more and more code with the "functionnal way", as it feels much cleaner (especially in JS using the beautiful LoDash library, but that's not the topic).
There actually has been quite some articles about this topic going around recently, like this very good one: A practical introduction to functional programming
But there's something that is never discussed there, it is memory management. Here are my questions:
- Do we agree that
functionalFilteruses more memory thannotFunctionalFilter? - Should this be taken into account when deciding how to write the
filterfunction? - Or does the garbage collector handles this perfectly (in most languages) because it is written the functional way?
Thanks