gilbarbara / react-inlinesvg

An SVG loader component for ReactJS

Home Page:https://codesandbox.io/s/github/gilbarbara/react-inlinesvg/tree/main/demo

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SVG content is reparsed even when it doesn't change

leeoniya opened this issue · comments

hi @gilbarbara,

first, thanks for this library :)

I noticed several areas where performance can be improved and would like to see what you think.

  1. i'm trying to pre-cache svg contents by path so that 0 fetch requests happen on initial load for statically-included icons. i was able to do this by exporting the global cacheStore, and pre-populating it with 'loaded' status cache objects and svg contents. i was hoping you can add this export to react-inlinesvg, so i can do this without a fork.
    const cacheStore: { [key: string]: StorageItem } = Object.create(null);
  2. i noticed that the svg sting is re-parsed into a DOM node, even when it does not change. is it possible to re-use the existing dom node? or alternatively, it would be cheaper to cache the parsed node in cacheStore, and then use cachedNode.clone(deep) instead of DOMParser(): https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
  3. some flow and regular expressions can be optimized, several examples here:
    const dataURI = src.match(/data:image\/svg[^,]*?(;base64)?,(.*)/);
    let inlineSrc;
    if (dataURI) {
    inlineSrc = dataURI[1] ? atob(dataURI[2]) : decodeURIComponent(dataURI[2]);
    } else if (src.indexOf('<svg') >= 0) {
    inlineSrc = src;
    }
    if (inlineSrc) {
    this.handleLoad(inlineSrc);
    return;
    }
  • } else if (src.indexOf('<svg') >= 0) { would be faster if it was src.startsWith('<svg') and also done prior to testing the more expensive regex variant
  • the regex variant /data:image\/svg[^,]*?(;base64)?,(.*)/ should probably start with /^ so that it only matches from start of line instead of potentially scanning the entire svg string before exiting with no match.

would you consider adding these or would you accept a PR?

thanks!
leon

Hello @leeoniya

  1. I'll export the cacheStore in 2.3.0
  2. Did you have problems with this or it's just an optimization urge? Because the DOMParse is quite an inexpensive operation at this level. I did think about this when I was implementing it and decided against caching as it would require a lot of code and I was already over my budget.
  3. Based on perf tests I've found indexOf is way faster than the rest.

And the difference between startsWith and regex is insignificant.

E.g.: https://www.measurethat.net/Benchmarks/Show/4797/1/js-regex-vs-startswith-vs-indexof#latest_results_block

thank you 🙏