错误表现从太多被捕获的错误? [英] bad performance from too many caught errors?

查看:114
本文介绍了错误表现从太多被捕获的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#(.NET 2.0)中有一个大型项目,它包含由SubSonic生成的非常大的代码块。是一个这样的try-catch导致一个可怕的性能命中?

  for(int x = 0; x< identifiers.Count ; x ++)
{decimal target = 0;
try
{
target = Convert.ToDecimal(assets [x + identifiers.Count * 2]); // target%
}
catch {targetEmpty = true; }}

发生的是如果传入的给定字段不是可以转换为十进制,它设置一个标志,然后在记录中进一步使用以确定其他内容。



问题是应用程序在字面上投掷了数十万例外,因为我正在解析30k的记录。整个过程大概需要10分钟的时间,而我的整体任务是改进一些时间,如果它的设计理念很糟糕,那么这似乎很容易挂上水果。



任何想法都会很有帮助(善意,这是一个悲惨的一天)



谢谢,
Chris

解决方案

使用控制流的异常通常是一个不好的做法(完全是因为您观察到的效率差)。您需要转换为 decimal 的数据类型?您可以使用 TryParse 方法或其他方法,如果输入不是预期格式,则不会抛出异常?



Decimal.TryParse 方法如果您通过返回 false 报告失败来解析字符串,则应该执行此操作:

  decimal d; 
if(Decimal.TryParse(str,out d))
//好的,使用小数'd'
else
//失败 - 做别的东西


I have a large project in C# (.NET 2.0) which contains very large chunks of code generated by SubSonic. Is a try-catch like this causing a horrible performance hit?

for (int x = 0; x < identifiers.Count; x++)
        {decimal target = 0;
            try
            {
                target = Convert.ToDecimal(assets[x + identifiers.Count * 2]); // target %
            }
            catch { targetEmpty = true;  }}

What is happening is if the given field that is being passed in is not something that can be converted to a decimal it sets a flag which is then used further along in the record to determine something else.

The problem is that the application is literally throwing 10s of thousands of exceptions as I am parsing through 30k records. The process as a whole takes almost 10 minutes for everything and my overall task is to improve that time some and this seemed like easy hanging fruit if its a bad design idea.

Any thoughts would be helpful (be kind, its been a miserable day)

thanks, Chris

解决方案

Using exceptions for control flow is generally a bad practice (exactly because of the poor efficiency that you're observing). What type of data do you need to convert to decimal? Could you use TryParse method or some other method that doesn't throw exception if the input is not in the expected format?

Decimal.TryParse method should do the trick if you're parsing strings as it reports failure by returnning false:

decimal d;
if (Decimal.TryParse(str, out d)) 
  // Ok, use decimal 'd'
else 
  // Failed - do something else

这篇关于错误表现从太多被捕获的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆