Swings ImageIcon 构造函数很慢 [英] Swings ImageIcon constructor is very slow

查看:51
本文介绍了Swings ImageIcon 构造函数很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅对此答案的评论以了解此问题的答案.TLDR:瓶颈在于缩放图像,但分析显示这是 ImageIcon 构造函数中的一个问题.

See comments to this answer for answer to this question. TLDR: The bottleneck is scaling the image, but profiling shows this as a problem in the ImageIcon constructor.

$ java -version
Picked up _JAVA_OPTIONS: -Dswing.aatext=true -Dawt.useSystemAAFontSettings=on
java version "1.7.0_45"
OpenJDK Runtime Environment (IcedTea 2.4.3) (ArchLinux build 7.u45_2.4.3-1-x86_64)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)

我的应用程序在启动时加载了 1,380 个图标.加载代码如下所示.使用 SSD 磁盘,ImageIcon 构造函数调用实际上比磁盘读取更昂贵(尽管磁盘读取可能会使用一些缓存..)

My application loads 1,380 icons at startup. The loading code is shown below. Using an SSD disk, the ImageIcon constructor calls is actually more expensive than the disk reads (the disk reads might use some cache though..)

加载图标需要 5.4 秒,其中 3.2 秒用于 ImageIcon 构造函数.

Loading the icons takes 5.4s, which 3.2s is spent in the ImageIcon constructor.

有没有办法加快 ImageIcon 的构建速度或使用其他方法?

Is there a way to speed up ImageIcon construction or use something else?

private ImageIcon setIcon(LogicalIcon iconInfo, int size) {
    ImageIcon icon = iconImages.get(iconInfo.getIconName());
    if(icon == null) {
        BufferedImage image = null;
        try {
            image = ImageIO.read(getBestPreviewIcon(iconInfo).getFile());
            icon = new ImageIcon(ImageUtils.scaleDownTo(image, new Dimension(size, size)));
            iconImages.put(iconInfo.getIconName(), icon);
        } catch (IOException e) {
            // FIXME: Add a "Missing Image" icon
            e.printStackTrace();
        }
    }
    setIcon(icon);
    return icon;
}

推荐答案

为了减少观察到的延迟,在 SwingWorker.您可以在每个可用时publish(),并将其添加到process() 实现中的List.可以选择和操作最初加载的图像,而其余的图像正在加载.让进度指示器监听属性更改.相关示例见此处这里.

To mitigate the observed latency, load and resample the images in the background thread of a SwingWorker. You can publish() each as it becomes available and add it to a List<Image> in your implementation of process(). Initially loaded images can be selected and manipulated, while the rest are loading. Let a progress indicator listen for property changes. Related examples are seen here and here.

总结评论的附录:

  • 工作线程可以增强用户对活跃度的感知.

一开始就知道图像的数量可以让进度指示器的粒度更细.

Knowing the number of images at the outset may allow finer granularity in the progress indicator.

针对瓶颈,scaleDownTo()方法出现调用getScaledInstance();参见 危险Image.getScaledInstance() 的详细信息,并考虑在此处检查的替代方案此处.

Focusing on the bottleneck, the scaleDownTo() method appears to call getScaledInstance(); see The Perils of Image.getScaledInstance() for details, and consider the alternatives examined here and here.

这篇关于Swings ImageIcon 构造函数很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆