gpt4 book ai didi

javascript - d3.js 图表框架建模

转载 作者:行者123 更新时间:2023-12-03 20:51:58 26 4
gpt4 key购买 nike

在考虑性能时哪种模型最适合在 d3.js 上构建图表?闭包类型还是构造函数原型(prototype)模型?

我为每种图表类型(如条形图、折线图、面积图)和一个用于绘制图表的通用模块设置了单独的模块。

这里使用闭包模式比原型(prototype)模式有什么优势

示例通用模块:

//闭包模式

function chart() {
var width = 720, // default width
height = 80,
scale,legends,axes; // default height

function my() {
// generate chart here, using `width` and `height`


}

my.width = function(value) {
if (!arguments.length) return width;
width = value;
return my;
};

my.height = function(value) {
if (!arguments.length) return height;
height = value;
return my;
};

return my;
}

var bar = new chart();
bar();

//原型(prototype)模式:

var chart = function(){
this.width =500;
this.height = 500;
this.initialize();
}
chart.prototype.initialize = function()
{
//generate chart here
}
var bar = new chart();

两者看起来很相似。但在考虑时哪一个更有优势

performance,redraw

最佳答案

根据该 jsperf 测试,它们看起来大致相同,因为这实际上取决于您的函数的作用。但从我选择的具体功能实现来看,带有变量提升的原型(prototype)模式在我测试的所有设备(chrome、safari、mobile safari)上都更快。

http://jsperf.com/javascript-prototype-vs-closure-performance

/**
* List prototype.
*/

function List() {
this.add = true;
this.items = [
{ x: 10, y: 10 },
{ x: 20, y: 20 },
{ x: 30, y: 30 },
{ x: 40, y: 40 },
{ x: 50, y: 50 },
{ x: 60, y: 60 },
{ x: 70, y: 70 },
{ x: 80, y: 80 },
{ x: 90, y: 90 },
{ x: 100, y: 100 }
];
}

/**
* Update without caching `items`.
*/

List.prototype.update1 = function(){
if (this.add) {
for (var i = 0, n = this.items.length; i < n; i++) {
this.items[i].x += 5;
this.items[i].y += 5;
}
} else {
for (var i = 0, n = this.items.length; i < n; i++) {
this.items[i].x -= 5;
this.items[i].y -= 5;
}
}

this.add = !this.add;
};

/**
* Update and cache `items`.
*/

List.prototype.update2 = function(){
var items = this.items;

if (this.add) {
for (var i = 0, n = items.length; i < n; i++) {
items[i].x += 5;
items[i].y += 5;
}
} else {
for (var i = 0, n = items.length; i < n; i++) {
items[i].x -= 5;
items[i].y -= 5;
}
}

this.add = !this.add;
};

/**
* List closure.
*/

function closure() {
var add = true;
var items = [
{ x: 10, y: 10 },
{ x: 20, y: 20 },
{ x: 30, y: 30 },
{ x: 40, y: 40 },
{ x: 50, y: 50 },
{ x: 60, y: 60 },
{ x: 70, y: 70 },
{ x: 80, y: 80 },
{ x: 90, y: 90 },
{ x: 100, y: 100 }
];

function list() {

}

list.update = function(){
if (add) {
for (var i = 0, n = items.length; i < n; i++) {
items[i].x += 5;
items[i].y += 5;
}
} else {
for (var i = 0, n = items.length; i < n; i++) {
items[i].x -= 5;
items[i].y -= 5;
}
}

add = !add;
};

return list;
}

var p = new List;
var c = closure();
var update = c.update;

http://jsperf.com/javascript-prototype-vs-closure-performance

关于javascript - d3.js 图表框架建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23294990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com