diff --git a/bundles/org.eclipse.swt/Eclipse SWT/win32/org/eclipse/swt/graphics/Image.java b/bundles/org.eclipse.swt/Eclipse SWT/win32/org/eclipse/swt/graphics/Image.java index 10841f925f..28f86d52d3 100644 --- a/bundles/org.eclipse.swt/Eclipse SWT/win32/org/eclipse/swt/graphics/Image.java +++ b/bundles/org.eclipse.swt/Eclipse SWT/win32/org/eclipse/swt/graphics/Image.java @@ -141,6 +141,34 @@ public final class Image extends Resource implements Drawable { private List> onDisposeListeners; + private record CachedHandle(ImageHandle handleContainer, int requestedWidth, int requestedHeight) { + + public void destroy() { + if (handleContainer != null) { + handleContainer.destroy(); + } + } + + public boolean isReusable(int height, int width) { + if(handleContainer == null) { + return false; + } + return (requestedHeight == height && requestedWidth == width) + || (handleContainer.height == height && handleContainer.width == width); + + } + + public long getHandle() { + if (handleContainer != null) { + return handleContainer.handle; + } + return -1; + } + }; + + // Initialize lastRequestedHandle with -1 for size-related fields to indicate uninitialized values + CachedHandle lastRequestedHandle = new CachedHandle(null, -1, -1); + private Image (Device device, int type, long handle, int nativeZoom) { super(device); this.type = type; @@ -826,19 +854,15 @@ interface HandleAtSizeConsumer { } void executeOnImageHandleAtSize(HandleAtSizeConsumer handleAtSizeConsumer, int widthHint, int heightHint) { - ImageData imageData; - imageData = this.imageProvider.loadImageDataAtSize(widthHint, heightHint); - executeOnImageHandle(handleAtSizeConsumer, imageData); -} - -private void executeOnImageHandle(HandleAtSizeConsumer handleAtSizeConsumer, ImageData imageData) { - ImageHandle handleContainer = init(imageData, -1); - long tempHandle = handleContainer.handle; - try { - handleAtSizeConsumer.accept(tempHandle, new Point(imageData.width, imageData.height)); - } finally { - handleContainer.destroy(); + if (!lastRequestedHandle.isReusable(heightHint, widthHint)) { + ImageData imageData; + imageData = this.imageProvider.loadImageDataAtSize(widthHint, heightHint); + lastRequestedHandle.destroy(); + ImageHandle handleContainer = init(imageData, -1); + lastRequestedHandle = new CachedHandle(handleContainer, widthHint, heightHint); } + handleAtSizeConsumer.accept(lastRequestedHandle.getHandle(), + new Point(lastRequestedHandle.handleContainer().width, lastRequestedHandle.handleContainer().height)); } /** @@ -1073,6 +1097,7 @@ void destroy () { private void destroyHandles() { destroyHandles(__ -> true); + lastRequestedHandle.destroy(); } @Override