gpt4 book ai didi

C# 静态类成员和 System.Windows.Controls.Image 性能问题

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:42 26 4
gpt4 key购买 nike

我目前正在调查应用程序中的性能问题并突出显示以下内容;

我有课-

public static class CommonIcons
{
...
public static readonly System.Windows.Media.ImageSource Attributes = typeof(CommonIcons).Assembly.GetImageFromResourcePath("Resources/attributes.png");
...
}

作为测试工具,我有以下代码使用此类来显示问题 -

for (int loop = 0; loop < 20000; loop++)
{
// store time before call

System.Windows.Controls.Image image = new System.Windows.Controls.Image
{
Source = CommonIcons.Attributes,
Width = 16,
Height = 16,
VerticalAlignment = VerticalAlignment.Center,
SnapsToDevicePixels = true
};

// store time after call
// log time between before and after

在循环开始时,时间差小于 0.001 秒,但经过 20000 秒后,时间差增加到 0.015 秒。

如果我不使用静态成员并直接引用我的图标,那么我就不会受到性能影响,即

for (int loop = 0; loop < 20000; loop++)
{
// store time before call

System.Windows.Controls.Image image = new System.Windows.Controls.Image
{
Source = typeof(CommonIcons).Assembly.GetImageFromResourcePath("Resources/attributes.png"),
Width = 16,
Height = 16,
VerticalAlignment = VerticalAlignment.Center,
SnapsToDevicePixels = true
};

// store time after call
// log time between before and after

但在我的真实世界程序中,我不想在每次调用时都创建图像源(增加内存直到垃圾回收),因此为什么要使用静态成员。但是,我也无法忍受性能下降。

有人可以解释为什么原始代码会造成这种性能损失吗?还有一个更好的解决方案来解决我正在尝试做的事情?

谢谢

最佳答案

这听起来像是与垃圾回收有关。我想知道 ImageSourceImage 之间是否存在某种耦合,这会导致您的第一种情况出现问题。您是否查看过测试工具在每种情况下的内存使用情况?

有趣的是,如果在每次迭代结束时将 Source 设置为 null,会发生什么情况?我知道这有点傻,但这是它作为测试工具的自然推论 :) 这可能进一步表明它是源和图像之间的链接...

关于C# 静态类成员和 System.Windows.Controls.Image 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com