1

在学习 Pluralsight 提供的一门设计模式课程时,它触及了享元模式,并在 node.js 中提供了一个示例。

课程中的示例将完全不使用享元与使用由多个字段连接在一起的唯一组合组成的享元进行对比,其中 1m 个对象有 160 个唯一组合。

我更进一步,只为独特的个体值创建享元,将享元的数量从 160 个减少到 15 个。

我的期望是,通过减少使用的享元数量,可以降低内存使用量。在我的测试中并非如此。

我怀疑我在概念上缺少一些东西。

注意我已经包含了一个可以提取并在节点中运行的小提琴。

与任务对象相关的部分详述如下:

// 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/

4

0 回答 0