我目前正在调查应用程序中的性能问题,并强调了以下内容;
我有一堂课——
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
}
但是在我的真实世界程序中,我不想在每次调用时都创建图像源(在垃圾收集之前增加内存),因此为什么使用静态成员。但是,我也无法忍受性能打击。
有人可以解释为什么原始代码会造成这种性能损失吗?对于我正在尝试做的事情也是一个更好的解决方案?
谢谢