在.NET中创建Font对象的成本

Tho*_*que 6 .net fonts

在我正在开发的应用程序中,我们使用DevExpress XtraGrid控件,该控件具有RowCellStyle允许自定义每个单元格样式的事件.此事件的事件处理程序通常如下所示:

private gridView1_RowCellStyle(object sender, RowCellStyleEventArgs e)
{
    if (/* Some condition */)
    {
        e.Appearance.Font = new Font(gridView1.Appearance.Font, FontStyle.Bold);
    }
}
Run Code Online (Sandbox Code Playgroud)

每次渲染单元格时都会调用此处理程序,因此它可以创建大量Font实例.所以我想知道这样做的成本......我做了一些实验,似乎每次都会创建一个新的HFONT手柄.我应该担心吗?对资源使用的影响有多大?

如果它对性能产生重大影响,是否应该有FontCache类或类似的东西?

注意:我知道如何解决问题(我只需要创建一次字体并每次都重复使用),我的问题是关于创建许多HFONT句柄的成本

Mar*_*ell 6

测试一下; 我通过重用获得了双重性能(在发布时,重用= 3000毫秒,重新创建= 4900毫秒)

using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
static class Program
{
    static void Main()
    {
        Button btn1, btn2;
        Form form = new Form
        {
            Controls = {
                (btn1 = new Button { Dock = DockStyle.Bottom, Text = "reuse" }),
                (btn2 = new Button { Dock = DockStyle.Bottom, Text = "recreate"})
            }
        };
        btn1.Click += delegate
        {
            var watch = Stopwatch.StartNew();
            using (var gfx = form.CreateGraphics())
            using (var font = new Font(SystemFonts.DefaultFont, FontStyle.Bold))
            {                
                gfx.Clear(SystemColors.Control);
                for (int i = 0; i < 10000; i++)
                {
                    gfx.DrawString("abc", font, SystemBrushes.ControlText, i % 103, i % 152);
                }
            }
            watch.Stop();
            form.Text = watch.ElapsedMilliseconds + "ms";
        };
        btn2.Click += delegate
        {
            var watch = Stopwatch.StartNew();
            using (var gfx = form.CreateGraphics())
            {
                gfx.Clear(SystemColors.Control);
                for (int i = 0; i < 10000; i++)
                {
                    using (var font = new Font(SystemFonts.DefaultFont, FontStyle.Bold))
                    {
                        gfx.DrawString("abc", font, SystemBrushes.ControlText, i % 103, i % 152);
                    }
                }
            }
            watch.Stop();
            form.Text = watch.ElapsedMilliseconds + "ms";
        };
        Application.Run(form);

    }
}
Run Code Online (Sandbox Code Playgroud)