From 61c21fcda7bd30221d2b5f9723345ad1d4b6955c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= Date: Fri, 22 Jan 2021 01:31:51 +0100 Subject: [PATCH] perf: "cache" blurhashes in dictionary --- components/Layout/Images/BlurhashCanvas.vue | 30 +++++++++++++++------ 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/components/Layout/Images/BlurhashCanvas.vue b/components/Layout/Images/BlurhashCanvas.vue index b044379c24a..340e8ee1393 100644 --- a/components/Layout/Images/BlurhashCanvas.vue +++ b/components/Layout/Images/BlurhashCanvas.vue @@ -15,6 +15,15 @@ import Vue from 'vue'; import getPixels from '~/plugins/workers/blurhash.worker'; +/** + * HACK: The cleanest way to do this would be to use an store. However, that required a deep watcher and, overall, + * I felt that it took longer to load the blurhashes using that approach than this. + * + * Blurhashes pixels *shouldn't* be required by any other component, so it might not make sense at all + * to move to the store approach and we might be fine with this one. + */ +const cache: { [hash: string]: Uint8ClampedArray } = {}; + export default Vue.extend({ props: { hash: { @@ -41,19 +50,23 @@ export default Vue.extend({ }; }, watch: { - hash(): void { - this.$nextTick(() => { - this.loading = true; - this.getPixels(); - }); + hash: { + immediate: true, + handler(): void { + this.$nextTick(() => { + this.loading = true; + if (cache[this.hash]) { + this.pixels = cache[this.hash]; + } else { + this.getPixels(); + } + }); + } }, pixels(): void { this.draw(); } }, - mounted() { - this.getPixels(); - }, methods: { draw(): void { const ctx = (this.$refs.canvas as HTMLCanvasElement).getContext('2d'); @@ -73,6 +86,7 @@ export default Vue.extend({ this.height, this.punch ); + cache[this.hash] = this.pixels; } catch { this.pixels = undefined; this.$emit('error');