现在的位置: 首页 > 综合 > 正文

effective c#读书笔记之一

2013年01月10日 ⁄ 综合 ⁄ 共 599字 ⁄ 字号 评论关闭

原则十六:不要创建无效的对象。

总结起来3点:

1、创建和销毁堆对象仍然需要消耗时间。

protected override void OnPaint( PaintEventArgs e )
{
  // Bad. Created the same font every paint event.
  using ( Font MyFont = new Font( "Arial", 10.0f ))
  {
    e.Graphics.DrawString( DateTime.Now.ToString(),
      MyFont, Brushes.Black, new PointF( 0,0 ));
  }
  base.OnPaint( e );
}

当程序中频繁调用OnPaint方法时,MyFont对象会频繁的被创建和销毁。

一个更好的方法是:

private readonly Font _myFont = new Font( "Arial", 10.0f );
protected override void OnPaint( PaintEventArgs e )
{
    e.Graphics.DrawString( DateTime.Now.ToString(),
      _myFont, Brushes.Black, new PointF( 0,0 ));
  
  base.OnPaint( e );
}

但此时应让_myFont字段所在的类实现IDisposal接口。

2、给最频繁使用的实例创建静态对象。

3、为了不可变的类型使用可变的创建者类。(StringBuilder)

抱歉!评论已关闭.