Search code examples
memory-managementfunctional-programmingmutable

Functional programming and memory management


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 functionalFilter uses more memory than notFunctionalFilter?
  • Should this be taken into account when deciding how to write the filter function?
  • Or does the garbage collector handles this perfectly (in most languages) because it is written the functional way?

Thanks


Solution

  • This is a slight aside but your functional filter should look like this:

    var functionalFilter = function (item) { return item.active; };

    and used like this: var filtered = objectArray.filter(functionFilter);

    The only "functional" thing about your "functionalFilter" is that it has no side effects. There is a lot more to functional programming and functional JS than that.

    As for memory. Yes it uses more... maybe... sort of. I am going on the assumption that you are passing in an array of objects based on the name. Using the builtin Array.filter is going to minimize this, but in your code the extra memory footprint is tiny.

    Objects in JS are passed by reference, that means that your new array is merely an array of pointers to the original objects. (Warning: this means changing them in filtered changes them in objectArray as well. Unless you do a deep clone) That array wrapper is relatively small and probably not even worth talking about in memory terms.