From 4fc0234ccc3724ebcde76da9c11a51e688f2cdee Mon Sep 17 00:00:00 2001 From: leriomaggio Date: Thu, 26 Aug 2021 03:02:52 +0100 Subject: [PATCH] Improved performance w/ cached content for ImageKeys.hasImage THe content of the setFolder is cached, filtering only images and key prefixes. Working on prefixes only to get rid of all .full or .fullborder possible variations. --- forge-core/src/main/java/forge/ImageKeys.java | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/forge-core/src/main/java/forge/ImageKeys.java b/forge-core/src/main/java/forge/ImageKeys.java index fe9360ab7a8..77553a9bd53 100644 --- a/forge-core/src/main/java/forge/ImageKeys.java +++ b/forge-core/src/main/java/forge/ImageKeys.java @@ -2,13 +2,11 @@ package forge; import forge.item.PaperCard; import forge.util.FileUtil; -import forge.util.ImageUtil; import forge.util.TextUtil; import org.apache.commons.lang3.StringUtils; import java.io.File; -import java.util.HashMap; -import java.util.Map; +import java.util.*; public final class ImageKeys { public static final String CARD_PREFIX = "c:"; @@ -68,9 +66,8 @@ public final class ImageKeys { } public static File getImageFile(String key) { - if (StringUtils.isEmpty(key)) { + if (StringUtils.isEmpty(key)) return null; - } final String dir; final String filename; @@ -220,14 +217,35 @@ public final class ImageKeys { //shortcut for determining if a card image exists for a given card //should only be called from PaperCard.hasImage() + static HashMap> cachedContent=new HashMap<>(); public static boolean hasImage(PaperCard pc) { Boolean editionHasImage = editionImageLookup.get(pc.getEdition()); if (editionHasImage == null) { String setFolder = getSetFolder(pc.getEdition()); editionHasImage = FileUtil.isDirectoryWithFiles(CACHE_CARD_PICS_DIR + setFolder); editionImageLookup.put(pc.getEdition(), editionHasImage); + if (editionHasImage){ + File f = new File(CACHE_CARD_PICS_DIR + setFolder); // no need to check this, otherwise editionHasImage would be false! + HashSet setFolderContent = new HashSet<>(); + for (String filename : Arrays.asList(f.list())) { + // TODO: should this use FILE_EXTENSIONS ? + if (!filename.endsWith(".jpg") && !filename.endsWith(".png")) + continue; // not image - not interested + setFolderContent.add(filename.split("\\.")[0]); // get rid of any full or fullborder + } + cachedContent.put(setFolder, setFolderContent); + } } + String[] keyParts = pc.getImageKeyFromSet().split(File.separator); + HashSet content = cachedContent.getOrDefault(keyParts[0], null); //avoid checking for file if edition doesn't have any images - return editionHasImage && getImageFile(ImageUtil.getImageKey(pc, false, true)) != null; + return editionHasImage && hitCache(content, keyParts[1]); + } + + private static boolean hitCache(HashSet cache, String filename){ + if (cache == null || cache.isEmpty()) + return false; + final String keyPrefix = filename.split("\\.")[0]; + return cache.contains(keyPrefix); } }