11ty / eleventy-img

Utility to perform build-time image transformations.

Home Page:https://www.11ty.dev/docs/plugins/image/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Slow initial cache population due to recomputation of hash

phuhl opened this issue · comments

I was wandering why, despite #116 the initial image generation was pretty slow (18 seconds for 14 pictures). So I dug into the code and found, that for each size-format combination the following happens:

  • resize
    • this.getFullStats
      • this.getHash
        • this.getFileContents and hash calculation (takes about 50ms+ per run)

Some console log output:

hash 74
hash 65
hash 66
hash 66
hash 65
hash 65
hash 65
hash 66
hash 67
hash 65
hash 65
DONE PROCESSING IMG 814

As you can see, the repeated calling of hash bumps up the time per image to just under a second for just this image.

All of the getHash calls are done on the same Image instance. Hence, I propose this change:

  getHash() {
+    if (this.computedHash) {
+      return this.computedHash;
+    }

    let hash = createHash("sha256");
    // ...
-     return base64hash.substring(0, this.options.hashLength);
+    const resultHash = base64hash.substring(0, this.options.hashLength);
+    this.computedHash = resultHash;
+    return resultHash;
  }

Would this have any downsides? For me it just meant, that an image generates in 50 ms instead of 800ms. My initial build time is down from 18 seconds to 1.5 seconds. 12x faster, not bad in my book 😄

I think, this is a duplicate of #170 but with the explanation with what's going on

This will ship with 3.0.0