1

While working my way through one of the Design Patterns courses that Pluralsight offer, it touched on the Flyweight Pattern, with an example in node.

The examples in the course contrasted not using flyweights at all with using a flyweight made up of the unique combinations of multiple fields concatenated together, of which there were 160 unique combinations across 1m objects.

I took this a step further by only creating flyweights for unique individual values which reduced the amount of flyweights from 160 to 15.

My expectation was that by reducing the number of flyweights used, it would lead to lower memory usage. Not the case in my tests.

I suspect there is something I'm missing conceptually.

N.B. I've included a fiddle which can be extracted and ran in node.

The section related to the Task object detailed below:

// Task Object
var Task = function (data) {
    this.name = data.name;

// This should be worst for memory. Unique values are duplicated across objects.
// 111MB for 1m
// Output:
/*Used memory 111.413132
  tasks: 1000000
  flyweights: 0*/
/*
this.priority = data.priority;
this.project = data.projects;
this.user = data.users;
this.completed = data.completed;*/

// Followed by this (160 flyweights)
// 98.95MB for 1m
// Adding flyweight 2NoneJonfalse
// Adding flyweight 4CoursesJontrue
// Adding flyweight 2NoneAmandafalse
// Adding flyweight 2CoursesJonfalse
// ..
// ..
// Adding flyweight 3NoneEricafalse
// Adding flyweight 3CoursesAmandafalse
// Adding flyweight 1ProjectAmandafalse
// Used memory 98.956656
// tasks: 1000000
// flyweights: 160
/*this.info = FlyweightFactory.get(data.priority + data.projects + data.users + data.completed);
this.info2 = FlyweightFactory.get(data.priority + data.projects + data.users + data.completed);
this.info3 = FlyweightFactory.get(data.priority + data.projects + data.users + data.completed);
this.info4 = FlyweightFactory.get(data.priority + data.projects + data.users + data.completed);*/   

// Followed by this (15 flyweights)
// This should be the best for memory?
// BUT THIS IS THE WORST (112MB) for 1m
// Output:
/*Adding flyweight 4
Adding flyweight Training
Adding flyweight Jon
Adding flyweight false
Adding flyweight 2
Adding flyweight None
Adding flyweight Erica
Adding flyweight true
Adding flyweight 3
Adding flyweight Project
Adding flyweight 1
Adding flyweight Nathan
Adding flyweight Courses
Adding flyweight 5
Adding flyweight Amanda
Used memory 111.974428
tasks: 1000000
flyweights: 15*/  
this.priority = FlyweightFactory.get(data.priority);
this.project = FlyweightFactory.get(data.projects);
this.user = FlyweightFactory.get(data.users);
this.completed = FlyweightFactory.get(data.completed);

};

http://jsfiddle.net/apc8nrmy/6/

parsfan82
  • 11
  • 2

0 Answers0