Skip to content

Commit 05c4c87

Browse files
committed
Attempt at performance improvements in recalculateVminsumForAffectedPixels
Replaced marked with a weird LRU-esque set thing. This array gets to be enormous but only the last few items are ever relevant. Removed enqueued, this also gets enormous and we can just rely on marked stopping these pixels getting re-processed.
1 parent 5140d40 commit 05c4c87

1 file changed

Lines changed: 24 additions & 10 deletions

File tree

SeamCarver.js

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,24 @@ const GREEN = 1;
55
const BLUE = 2;
66
const BORDER_ENERGY = 1000;
77

8+
class LRUCache {
9+
constructor(max = 10) {
10+
this.max = max;
11+
this.cache = new Map();
12+
}
13+
14+
has(key) { return this.cache.has(key); }
15+
set(key) {
16+
if (this.cache.size > this.max) {
17+
this.cache.delete(this.cache.keys().next().value);
18+
}
19+
if (this.cache.has(key)) {
20+
return;
21+
}
22+
this.cache.set(key, 1);
23+
}
24+
}
25+
826
/** Seam carver removes low energy seams in an image from HTML5 canvas. */
927
class SeamCarver {
1028

@@ -310,9 +328,7 @@ class SeamCarver {
310328
* Recalculate vminsum for affected pixels
311329
*/
312330
recalculateVminsumForAffectedPixels(queue) {
313-
var marked = {};
314-
var enqueued = {};
315-
var maxRow = -1;
331+
var marked = new LRUCache(16);
316332
// start at second to last row
317333
var row = this.height - 2;
318334
var enqueuedCols = queue[row];
@@ -327,9 +343,11 @@ class SeamCarver {
327343
if (enqueuedCols.length === 0) enqueuedCols = queue[--row];
328344

329345
// already explored this pixel
330-
if (marked[pixelIndex]) continue;
346+
if (marked.has(pixelIndex)) {
347+
continue;
348+
}
331349

332-
marked[pixelIndex] = true;
350+
marked.set(pixelIndex);
333351

334352
var nodeEnergy = this.energyMatrix[col][row];
335353
var oldVminsum = this.minsumMatrix[col][row];
@@ -355,11 +373,7 @@ class SeamCarver {
355373

356374
// enqueue three affected children from row above
357375
for (var i = Math.max(col - 1, 0); i < Math.min(col + 2, lastCol + 1); i ++) {
358-
var childIndex = this.pixelToIndex(i, row - 1);
359-
if (!enqueued[childIndex]) {
360-
enqueued[childIndex] = true;
361-
queue[row - 1].push(i);
362-
}
376+
queue[row - 1].push(i);
363377
}
364378
}
365379
}

0 commit comments

Comments
 (0)