我本无心

instinct

博客园 首页 新随笔 联系 订阅 管理

今天改了程序中的一段代码,分享给大家。

如何改进性能:
1.需要我们回头来再次审查已有的代码;
2.思考在程序运行实际情况中那些地方要执行多次,那些地方很少执行,重点改进关键地方;
3.变换实现的方法:

如一段数据库比较的代码:
开始我这样实现:
      //字段存在标记
   bool bFind;

   //循环读取服务器表中字段
   foreach(DataRow serverRow in structureServer.Tables["Column"].Select("TABLE_NAME='"+tablename+"'"))
   {
    //读取服务器表中字段信息
    ColumnInfo colServer = ColumnInfo.GetColumnInfo( serverRow);

    //重置标记
    bFind = false;

    //循环读取客户端表中字段
    foreach(DataRow clientRow in structureClient.Tables["Column"].Select("TABLE_NAME='"+tablename+"'"))
    {
     //读取客户端表中字段信息
     ColumnInfo colClient = ColumnInfo.GetColumnInfo( clientRow);

    
     if(colServer.ColumnName == colClient.ColumnName)
     {
      //比较名称相同的字段
      if(colServer.Compare(colClient)==false)
      {
       //如果不一样就同步
       colServer.SyncColumn(ref cn,colClient);      
      }
      bFind = true;
      break;
     }
    }
    //没有找到相应的字段,创建字段
    if(bFind==false)
    {
     colServer.SyncColumn(ref cn);
    }

   }


   return true;

上面程序看起来没什么大问题,可以运行,但是如果表中字段超过500个,性能非常差,几乎需要半小时比较才能完成


改进后

    //用两个哈希表作比较
   Hashtable htServerRow = new Hashtable();
   Hashtable htClientRow = new Hashtable();

  
   //循环读取服务器表中字段
   foreach(DataRow serverRow in structureServer.Tables["Column"].Select("TABLE_NAME='"+tablename+"'"))
   {
    ColumnInfo colServer = ColumnInfo.GetColumnInfo( serverRow);
    htServerRow.Add(colServer.ColumnName,colServer);
   }

   //循环读取客户端表中字段
   foreach(DataRow clientRow in structureClient.Tables["Column"].Select("TABLE_NAME='"+tablename+"'"))
   {
    ColumnInfo colClient = ColumnInfo.GetColumnInfo( clientRow);
    htClientRow.Add(colClient.ColumnName,colClient);
   }
   //比较
   foreach(string name in htServerRow.Keys)
   {
    if(htClientRow.Contains(name))
    {
     ColumnInfo colServer = ((ColumnInfo)htServerRow[name]);

     ColumnInfo colClient = ((ColumnInfo)htClientRow[name]);

     if(colServer.Compare(colClient)==false)
     {
      colServer.SyncColumn(ref cn,colClient);      
     }
    }
    else
    {
     ((ColumnInfo)htServerRow[name]).SyncColumn(ref cn);
    }
   }

改进后性能非常好,需要半小时得工作一分钟之内就完成了

  

posted on 2004-12-28 20:13  我本无心  阅读(673)  评论(0编辑  收藏  举报