如何优化/加速代码执行C#,Windows.Net

时间:2009-01-07 11:25:52

标签: c#

我有以下代码块我尝试在优化部分进行优化

DataSet dsLastWeighing = null;
DataSet ds = null;
DataSet dsWeight = null;
string strQuery = string.Empty;
string strWhere = string.Empty;
Database db = null;

#region Original Code Block
            try
            {   
                db = DatabaseFactory.CreateDatabase();

                strWhere = "WHERE SESSION_ID = '"+pSessionID+"'"; 
                strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("DeleteWeightRecent",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                db.ExecuteNonQuery(System.Data.CommandType.Text, strQuery);

                strWhere = "WHERE LAB_ID = 0";
                strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("InsertWeightRecent",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                db.ExecuteNonQuery(System.Data.CommandType.Text, strQuery);

                strWhere = strWhere = "WHERE SESSION_ID = '"+pSessionID+"'"; 
                strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("GetPatientID",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                ds = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strQuery);

                foreach(DataRow dr in ds.Tables[0].Rows)
                {
                    if (db.ToString() == "Microsoft.Practices.EnterpriseLibrary.Data.SqlBase.SqlBaseDatabase")
                    {
                        strWhere = "WHERE LAB_ID=0 AND PAT_ID ="+ int.Parse(dr["PAT_ID"].ToString())+" AND WHEN IN(SELECT MAX(WHEN) FROM PATIENT_LAB WHERE LAB_ID=0 AND PAT_ID="+ int.Parse(dr["PAT_ID"].ToString())+")"; 
                    }
                    else if (db.ToString() == "Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase")
                    {
                        strWhere = "WHERE LAB_ID=0 AND PAT_ID ="+ int.Parse(dr["PAT_ID"].ToString())+" AND [WHEN] IN(SELECT MAX([WHEN]) FROM PATIENT_LAB WHERE LAB_ID=0 AND PAT_ID="+ int.Parse(dr["PAT_ID"].ToString())+")"; 
                    }
                    strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("GetWeight",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");

                    strMain.append(strQuery+" ");
                    dsWeight = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strQuery);


                    foreach(DataRow drWeight in dsWeight.Tables[0].Rows)
                    {                           
                        strWhere =  "WHERE PAT_ID = "+int.Parse(dr["PAT_ID"].ToString())+" AND SESSION_ID ='"+pSessionID+"'";
                        strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("UpdateWeightRecent",db.ToString(),pFacilityID,pSessionID,strWhere,decimal.Parse(drWeight["LEVEL"].ToString()),DateTime.Parse(drWeight["WHEN"].ToString()).ToUniversalTime(),int.Parse(drWeight["IS_BAD"].ToString()),drWeight["NOTE"].ToString());
                        db.ExecuteNonQuery(System.Data.CommandType.Text, strQuery); 
                    }

                }

                strWhere = " ORDER BY W.IS_BAD DESC, P.LASTNAME ASC, P.FIRSTNAME ASC,P.MIDDLENAME ASC";
                strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("GetPatientLastWeight",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                dsLastWeighing = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strQuery);                   
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                db = null;
                ds= null;
                dsWeight= null;
            }
            return dsLastWeighing;
            #endregion




--Optimized Section--

    #region Optimized Code Block

            try
            {   
                StringBuilder strMain=new StringBuilder();
                db = DatabaseFactory.CreateDatabase();

                //StartTime=DateTime.Now.ToLongTimeString();
                strWhere = "WHERE SESSION_ID = '"+pSessionID+"'"; 
                strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("DeleteWeightRecent",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                //EndTime=DateTime.Now.ToLongTimeString();
                //db.ExecuteNonQuery(System.Data.CommandType.Text, strQuery);
                strMain.append(strQuery+" ");

                strWhere = "WHERE LAB_ID = 0";

                //StartTime=DateTime.Now.ToLongTimeString();
                  strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("InsertWeightRecent",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                //EndTime=DateTime.Now.ToLongTimeString();

                //db.ExecuteNonQuery(System.Data.CommandType.Text, strQuery);
                strMain.append(strQuery+" ");

                strWhere = strWhere = "WHERE SESSION_ID = '"+pSessionID+"'"; 
                //StartTime=DateTime.Now.ToLongTimeString();
                  strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("GetPatientID",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                //EndTime=DateTime.Now.ToLongTimeString();
                //ds = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strQuery);

                strMain.append(strQuery+" ");
                //StartTime=DateTime.Now.ToLongTimeString();
                 ds = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strMain.ToString());
                //EndTime=DateTime.Now.ToLongTimeString();

                strMain=null;


                foreach(DataRow dr in ds.Tables[0].Rows)
                {
                    //StartTime=DateTime.Now.ToLongTimeString();
                    if (db.ToString() == "Microsoft.Practices.EnterpriseLibrary.Data.SqlBase.SqlBaseDatabase")
                    {
                        strWhere = "WHERE LAB_ID=0 AND PAT_ID ="+ int.Parse(dr["PAT_ID"].ToString())+" AND WHEN IN(SELECT MAX(WHEN) FROM PATIENT_LAB WHERE LAB_ID=0 AND PAT_ID="+ int.Parse(dr["PAT_ID"].ToString())+")"; 
                    }
                    else if (db.ToString() == "Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase")
                    {
                        strWhere = "WHERE LAB_ID=0 AND PAT_ID ="+ int.Parse(dr["PAT_ID"].ToString())+" AND [WHEN] IN(SELECT MAX([WHEN]) FROM PATIENT_LAB WHERE LAB_ID=0 AND PAT_ID="+ int.Parse(dr["PAT_ID"].ToString())+")"; 
                    }
                    strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("GetWeight",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");

                    strMain.append(strQuery+" ");
                    //EndTime=DateTime.Now.ToLongTimeString();
                    //dsWeight = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strQuery);

                    /*
                    foreach(DataRow drWeight in dsWeight.Tables[0].Rows)
                    {                           
                        strWhere =  "WHERE PAT_ID = "+int.Parse(dr["PAT_ID"].ToString())+" AND SESSION_ID ='"+pSessionID+"'";
                        strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("UpdateWeightRecent",db.ToString(),pFacilityID,pSessionID,strWhere,decimal.Parse(drWeight["LEVEL"].ToString()),DateTime.Parse(drWeight["WHEN"].ToString()).ToUniversalTime(),int.Parse(drWeight["IS_BAD"].ToString()),drWeight["NOTE"].ToString());
                        db.ExecuteNonQuery(System.Data.CommandType.Text, strQuery); 
                    }
                    */
                }


                dsWeight = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strMain.ToString());
                strMain=null;
                //StartTime=DateTime.Now.ToLongTimeString();
                for(int i=0;i<dsWeight.Tables.Count;i++)
                {
                    foreach(DataRow drWeight in dsWeight.Tables[i].Rows)
                    {                           
                        strWhere =  "WHERE PAT_ID = "+int.Parse(dr["PAT_ID"].ToString())+" AND SESSION_ID ='"+pSessionID+"'";
                        strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("UpdateWeightRecent",db.ToString(),pFacilityID,pSessionID,strWhere,decimal.Parse(drWeight["LEVEL"].ToString()),DateTime.Parse(drWeight["WHEN"].ToString()).ToUniversalTime(),int.Parse(drWeight["IS_BAD"].ToString()),drWeight["NOTE"].ToString());
                        strMain.append(strQuery+" ");
                        //db.ExecuteNonQuery(System.Data.CommandType.Text, strQuery);   
                    }
                }
                db.ExecuteNonQuery(System.Data.CommandType.Text, strMain.ToString());   
                //EndTime=DateTime.Now.ToLongTimeString();

                //StartTime=DateTime.Now.ToLongTimeString();
                strWhere = " ORDER BY W.IS_BAD DESC, P.LASTNAME ASC, P.FIRSTNAME ASC,P.MIDDLENAME ASC";
                strQuery = SQ.BusinessLogic.SQLQueryFactory.GetPatientLastWeighing("GetPatientLastWeight",db.ToString(),pFacilityID,pSessionID,strWhere,0,DateTime.Now.ToUniversalTime(),0,"");
                dsLastWeighing = (DataSet) db.ExecuteDataSet(System.Data.CommandType.Text, strQuery);   
                //EndTime=DateTime.Now.ToLongTimeString();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                db = null;
                ds= null;
                dsWeight= null;
            }
            return dsLastWeighing;


            #endregion

可以进一步优化..只需专注于最小化循环..我没有得到任何进一步的想法..任何帮助将不胜感激

5 个答案:

答案 0 :(得分:8)

我建议:

  • 使用参数化SQL
  • 摆脱catch块,或至少使用“throw”而不是“throw ex”,这样你就不会丢失信息
  • 摆脱最后一块 - 它没有帮助你
  • 在首次需要时声明变量,而不是在方法顶部的所有变量
  • 将方法分解为更易于管理的部分

完成所有这些工作后,您将能够更好地调整性能。此时,分析应用程序并查看痛点实际上是在.NET代码中还是在与数据库的交互中。根据我的经验,数据库应用程序通常通过以下方式得到改进:

  • 改进SQL查询
  • 减少往返次数
  • 优化数据库(应用索引等)

答案 1 :(得分:4)

也许您已经优化了SQL字符串的创建,但我认为这与花生与SQL服务器通信所需的时间相比较。

通过优化字符串赢得了几毫秒,但使用数据集却松了很多。

我认为你应该首先关注这一部分。而且不仅仅是数据集,如果优化SQL服务器还有很多工作要做。也许扔进存储过程,看看索引等。

此外,对于SQL注入攻击,此代码根本不安全。你应该使用参数。

答案 2 :(得分:0)

如果C#的StringBuilder与Java的StringBuilder类似,那么就像

这样的行
strMain.append(strQuery+" ");

是一个肯定的迹象,表明您还没有理解StringBuilder的用途。

在Java中,该行将被编译为

strMain.append(new StringBuilder().append(strQuery).append(" ").toString());

我很确定

答案 3 :(得分:0)

我不知道循环,但这里有几个指针

  • 不要在stringbuilders中使用strQuery +“”系统。也附加“”。
  • 如果您正在寻找优化的SQL性能,那么您使用的是数据集。改为使用Datareader。
  • 听Jon Skeet。

我认为您的代码需要重新设置如何模拟以获得良好的性能提升。我个人可以尽量避免使用数据集。

答案 4 :(得分:0)

小问题:strWherestring,您正在进行大量操作。你最好使用StringBuilder来做这件事。您也可以通过使用合适的长度初始化StringBuilder来获得一些好处。