如何使用jquery在大的dom中获得良好的性能
how to get the good performance in the big dom with jquery?
我用jquery用Javascript编写了一个小程序。
var mlife = function (i, j, alive) {
var face = '<div class="life" id="l_' + i + '_' + j + '"/>';
var f = $(face);
var ps = new Array();
//var interval;
this.draw=function() {
if (alive) {
f.addClass('l');
} else {
f.removeClass('l');
}
};
this.aliveCheck=function() {
var alivecount = 0;
for (var i = 0; i < ps.length; i++) {
var el = $('#l_' + ps[i]);
if (el.length > 0) {
if (el.hasClass('l')) {
alivecount++;
}
}
}
if (alive) {
if (alivecount < 2) {
alive = false;
} else if (alivecount == 2 || alivecount == 3) {
alive = alive;
} else if (alivecount > 3) {
alive = false;
}
} else {
if (alivecount == 3) {
alive = true;
}
}
//_draw();
};
this.getface = function () {
return f;
};
function _init() {
ps.push((i - 1) + '_' + (j - 1));
ps.push((i - 1) + '_' + (j + 1));
ps.push((i + 1) + '_' + (j - 1));
ps.push((i + 1) + '_' + (j + 1));
ps.push(i + '_' + (j - 1));
ps.push(i + '_' + (j + 1));
ps.push((i + 1) + '_' + j);
ps.push((i - 1) + '_' + j);
if (alive) {
f.addClass('l');
}
};
_init();
}
$(function () {
var html = "";
var alive = false;
var cells = new Array();
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 100; j++) {
if (Math.random() > 0.90) {
alive = true;
} else {
alive = false;
}
var l = new mlife(i, j, alive);
cells.push(l);
$('#show').append(l.getface());
}
}
setInterval(allAliveCheck,1000);
function allAliveCheck(){
for(var i=0;i<cells.length;i++){
cells[i].aliveCheck();
}
for(var i=0;i<cells.length;i++){
cells[i].draw();
}
}
});
http://jsfiddle.net/chanjianyi/upgvzm78/1/
这是关于"生命的游戏":http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
但我发现它的性能很差,控制了很多分区。
有人想优化我的程序吗?
jQuery速度较慢。抛弃jQuery,它会运行得更快。下面是一个例子。
var mlife = function(i, j, alive) {
// var face = '<div class="life" id="l_' + i + '_' + j + '"/>';
var f = document.createElement('div');
f.className = 'life';
f.id = 'l_' + i + '_' + j;
var ps = [];
//var interval;
this.draw = function() {
if (alive) {
f.classList.add('l');
} else {
f.classList.remove('l');
}
};
this.aliveCheck = function() {
var alivecount = 0;
for (var i = 0; i < ps.length; i++) {
var el = document.getElementById('l_' + ps[i]);
if (el) {
if (el.classList.contains('l')) {
alivecount++;
}
}
}
if (alive) {
if (alivecount < 2) {
alive = false;
} else if (alivecount == 2 || alivecount == 3) {
alive = alive;
} else if (alivecount > 3) {
alive = false;
}
} else {
if (alivecount == 3) {
alive = true;
}
}
//_draw();
};
this.getface = function() {
return f;
};
function _init() {
ps.push((i - 1) + '_' + (j - 1));
ps.push((i - 1) + '_' + (j + 1));
ps.push((i + 1) + '_' + (j - 1));
ps.push((i + 1) + '_' + (j + 1));
ps.push(i + '_' + (j - 1));
ps.push(i + '_' + (j + 1));
ps.push((i + 1) + '_' + j);
ps.push((i - 1) + '_' + j);
if (alive) {
f.classList.add('l');
}
};
_init();
}
var html = "";
var alive = false;
var cells = [];
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 100; j++) {
if (Math.random() > 0.90) {
alive = true;
} else {
alive = false;
}
var l = new mlife(i, j, alive);
cells.push(l);
document.getElementById('show').appendChild(l.getface());
}
}
setInterval(allAliveCheck, 1000);
function allAliveCheck() {
for (var i = 0; i < cells.length; i++) {
cells[i].aliveCheck();
}
for (var i = 0; i < cells.length; i++) {
cells[i].draw();
}
}
#show {
width: 500px;
height: 500px;
border: 0px solid red;
}
.life {
width: 5px;
height: 5px;
background: black;
float: left;
}
.l {
background: blue;
}
<body>
<div id="show"></div>
</body>
考虑将操场数据存储为一个简单的数组,而不是将其存储在HTML元素中。通过这种方式,您可以使任意前端显示相同的数据。画布或一个简单的预格式化文本块可以在视觉上给出相同的结果;任何一个都可能比一堆div表现得更好。
我建议把你的代码发布在codereview.stackeexchange.com上。这个代码还有很大的改进空间;CR是学习如何改进它的好场所。
下面是一个简单CA的例子(这是我几周前为了好玩而做的事情)。它使用一堆button
元素来显示网格,但请注意,显示例程可以很容易地与画布或其他机制交换。
//
// Cell
//
function Cell(grid, x, y) {
/** @type Grid */
this.grid = grid;
/** @type number */
this.x = x;
/** @type number */
this.y = y;
}
Cell.prototype.getAdjacent = function() {
var cellX = this.x,
cellY = this.y,
grid = this.grid,
result = [],
cell;
for (var y = cellY - 1; y <= cellY + 1; y++) {
for (var x = cellX - 1; x <= cellX + 1; x++) {
if (x == cellX && y == cellY) {
continue;
}
cell = grid.getCell(x, y);
cell && result.push(cell);
}
}
return result;
};
//
// Grid
//
function Grid(width, height) {
/** @type number */
this.width = width;
/** @type number */
this.height = height;
/** @type Array.<Cell> */
this.cells = [];
this.initCells();
}
Grid.prototype.initCells = function() {
var width = this.width,
height = this.height,
cells = this.cells;
for (var y = height; y--;) {
for (var x = width; x--;) {
cells.unshift(new Cell(this, x, y));
}
}
};
Grid.prototype.getCell = function(x, y) {
var width = this.width,
height = this.height,
cells = this.cells;
if (x >= 0 && y >= 0 && x < width && y < height) {
return cells[x + y * width];
}
};
Grid.prototype.each = function(callback) {
var cells = this.cells,
cellCount = cells.length;
for (var i = 0; i < cellCount; i++) {
callback(cells[i], i);
}
};
//
// GridDisplay
//
function GridDisplay(grid, element) {
/** @type Grid */
this.grid = grid;
/** @type Element */
this.element = element;
}
GridDisplay.prototype.drawCell = function(cell) {
var display = this,
button = document.createElement('button');
button.style.border = '1px outset white';
if (cell.value) {
button.style.backgroundColor = 'black';
}
button.onclick = function(event) {
if (cell.value) {
cell.value = false;
} else {
cell.value = true;
}
display.draw();
};
return button;
};
GridDisplay.prototype.draw = function() {
var display = this,
grid = this.grid,
buttons = this.element.getElementsByTagName('button'),
container;
if (buttons.length) {
grid.each(function(cell, i) {
if (cell.value) {
buttons[i].style.backgroundColor = 'black';
} else {
buttons[i].style.backgroundColor = null;
}
});
return;
}
this.element.innerHTML = '';
container = document.createElement('div');
grid.each(function(cell, i) {
if (!cell.x) {
container.appendChild(document.createElement('br'));
}
container.appendChild(display.drawCell(cell));
});
this.element.appendChild(container);
};
//
// Game
//
function Game(width, height, rule) {
// The standard Game of Life is symbolised as "B3/S23":
// A cell is "Born" if it has exactly 3 neighbours,
// "Stays alive" if it has 2 or 3 living neighbours.
var bornSurvive = rule.match(/'d+/g);
this.birthRule = bornSurvive[0];
this.survivalRule = bornSurvive[1];
this.grid = new Grid(width, height);
this.gridDisplay = new GridDisplay(this.grid, board);
this.gridDisplay.draw();
}
Game.prototype.tick = function() {
var grid = this.grid,
survivalRule = this.survivalRule,
birthRule = this.birthRule;
grid.each(function(cell, i) {
var neighbors = cell.getAdjacent();
var liveNeighborCount = 0;
for (var j = 0; j < neighbors.length; j++) {
if (neighbors[j].value) {
++liveNeighborCount;
}
}
if (cell.value) {
cell.nextValue = ~survivalRule.indexOf(liveNeighborCount);
} else {
cell.nextValue = ~birthRule.indexOf(liveNeighborCount);
}
});
grid.each(function(cell) {
cell.value = cell.nextValue;
});
this.gridDisplay.draw();
};
function createButton(label, callback) {
var button = document.createElement('input');
button.type = 'button';
button.value = label;
button.onclick = callback;
document.body.appendChild(button);
}
var board = document.getElementById('board');
var game;
var interval;
createButton('new game', function() {
clearInterval(interval);
board.innerHTML = '';
game = new Game(50, 50, prompt('Enter a rule', 'B3/S23'));
});
createButton('randomize', function() {
var cells = game.grid.cells;
clearInterval(interval);
for (var i = 0; i < cells.length; i++) {
cells[i].value = Math.random() * 2 | 0;
}
game.gridDisplay.draw();
});
createButton('step', function() {
clearInterval(interval);
game.tick();
});
createButton('go', function() {
clearInterval(interval);
interval = setInterval(function () {
game.tick()
}, 100);
});
createButton('stop', function() {
clearInterval(interval);
});
body { font: 10pt sans-serif; }
div { font-size: 1px; }
button { width: 8px; height: 8px; margin:0; padding: 0; vertical-align: middle; }
<div id="board"></div>
使用<div>
s是一个非常有趣的想法:)
通常我真的很喜欢SVG用于网络上的图形,但这是一个很好的例子,其中<canvas>
元素很有意义,我的意思是,无论如何,你基本上都使用像素。
因此,如果你想保留<div>
,请遵循Cerbrus的建议,去掉hasClass()
,或者至少尝试原生el.classList.contains()
。根据这个jsperf,这应该会快得多。但最好将它放在JS中的一个变量中。
作为一个预告片,看看这个生活的画布游戏:http://pmav.eu/stuff/javascript-game-of-life-v3.1.1/
- Javascript性能-在dom上迭代并添加侦听器
- 样式 DOM 上的 $.before() 性能问题
- 在大型DOM上使用jQuery .nextTil的性能
- 性能问题:存储对DOM元素的引用与使用选择器相比
- Web应用程序性能:SVG、Canvas或Dom Manipulation
- 获取DOM元素的性能差异
- 更多的 DOM 元素会产生性能问题
- 为什么 DOM 读/写操作的微小重新排序会导致巨大的性能差异
- 向 DOM 添加一个简单的图像标记,而不是使用 GWT 控件以获得更好的 JS 运行时性能
- Javascript DOM与XSLT转换的性能对比
- 由于大量dom元素导致的性能问题
- 数百个DOM元素的JavaScript事件侦听器性能
- 如何使用jquery在大的dom中获得良好的性能
- 使用CSS3的供应商特定前缀的性能和DOM加载
- 为DOM深处的元素设置动画真的会影响性能吗
- IE8中的jQuery和DOM操作性能问题
- 当DOM中的元素太多时,Angular的ng类会出现性能问题
- 响应式Web设计中DOM操作的性能
- 在jQuery初始化之前进行条件DOM检查的性能
- DOM内脚本和样式的性能优势