简体   繁体   中英

reading SVG icon files from disk compared to caching the SVG data?

I have an Electron app using d3 and it uses lots of small (50 x 50 px) SVG icons – there could be a 100 or more, with many of duplicates.

The icons are read from disk using fs and returned to my d3 creation routine. The user is able to switch icons when they are editing their project. They could use one or two icons over and over or use any of the 50 icons that are available for them to select from.

I thought I was being clever and wrote an "icon manager" which caches the SVG data in an array after it is read by fs , so that if the icon is used multiple times, the "in memory" version can be returned instead of reading from disk again.

I wrote the code over a year ago and had to go into it today to fix an issue. Looking at it now, I am wondering it is all just silly: that fs hitting the disk compared to walking through an array is a pointless and even potentially "negative" optimization – that as the number of items in the array grows, the "cost" gets higher.

Am I working too hard here for no reason?


const fs = require('fs');
const iconLib = [];

exports.getIcon = function (iconName, iconPath) {

    for (let i = 0; i < iconLib.length; i++) {
        if (iconLib[i].iconName == iconName) {
            return iconLib[i].iconData;
        }
    }

    if (fs.existsSync(iconPath)) {
        let data = fs.readFileSync(iconPath, 'utf8');
        iconLib.push({ iconName: iconName, iconData: data })
        return data;
    } else {
        // TODO return something useful
        return 0;
    }
};

Instead of an array that must be traversed on every retrieval, how about using JavaScript's built-in Map ?

To add an icon to the map:

    const iconMap = new Map();

    function cacheIcon(iconName, iconData) {
      iconMap.set(iconName, iconData);
    }

To retrieve icon from the map:

    iconData = iconMap.get(iconName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM