23

我将值存储为字符串,DataTable其中每个值都可以真正表示一个int, double, or string(在从外部数据源导入过程中,它们都被转换为字符串)。我需要测试并查看每个值的真正类型。

什么对应用程序更有效(或者没有实际区别)?

  1. 尝试转换为int(然后double)。如果转换有效,则返回true. 如果抛出异常,则返回false
  2. 正则表达式旨在匹配intor的模式double
  3. 还有什么方法?
4

5 回答 5

10

将使用 double.TryParse,它具有性能优势。

于 2008-08-05T07:54:12.613 回答
5

我想说,不要太担心这样的微观表现。最好只是让一些东西工作,然后让它尽可能清晰、简洁和易于阅读。你能做的最糟糕的事情就是牺牲可读性以获得微不足道的性能。

最后,处理性能问题的最佳方法是将它们保存到当您有数据表明存在实际性能问题时……否则您将花费​​大量时间进行微优化并实际上导致更高的维护成本稍后的。

如果您发现这种解析情况确实是您的应用程序的瓶颈,那么是时候尝试找出解决问题的最快方法是什么了。我认为杰夫(和许多其他人)已经在博客上写了很多关于这类事情的文章。

于 2008-08-05T08:04:22.093 回答
5

根据您是否使用优化进行编译,您将获得不同方法的不同结果。你基本上有几个选择:

object o;

//checking with is
o is int

//check type
o.GetType() != typeof( int )

//cast and catch exception
try{ int j = (int) o; } 
catch {}

//use the tryparse
int.TryParse( Convert.ToString( o ), out j )

您可以轻松地设置一个控制台应用程序,尝试这 10,000 次中的每一个并返回每个的持续时间(测试 o 何时为 int 以及何时为其他值)。

如果对象确实持有 int,则该try-catch方法是最快的,如果不持有 int,则该方法是迄今为止最慢的(甚至比 还要慢GetType)。 int.TryParse如果你有一个字符串,它会很快,但如果你有一个未知的对象,它会更慢。

有趣的是,在 .Net 3.5 和优化开启的情况下,检查的时间与o 实际上是 into is int的时间相同。如果 o 实际上是别的东西,它只会稍微慢一点。try-catcho is int

烦人的是,如果您执行以下操作,FxCop 会发出警告:

if( o is int )
    int j = (int) o;

但我认为这是 FxCop 中的一个错误——它不知道 int 是一种值类型,因此建议您o as int改用它。

如果您的输入始终是字符串int.TryParse是最好的,否则is操作员是最快的。

因为你有一个字符串,我会看看你是否需要知道它是一个 int,而不是一个 double。如果int.TryParse通过,那么double.TryParse您可以减少一半的检查次数 - 返回双精度或字符串,并在您期望一个 int 时对双精度进行下限。

于 2008-08-10T17:43:14.273 回答
5

The trouble you have is that there could be situations where the answer could be all three types.

3 could be an int, a double or a string!

It depends upon what you are trying to do and how important it is that they are a particular type. It might be best just to leave them as they are as long as you can or, alternatively, some up with a method to mark each one (if you have control of the source of the original string).

于 2008-09-23T21:38:19.677 回答
3

我个人会使用 int.tryparse,然后使用 double.tryparse。这些方法的性能非常快。他们都返回一个布尔值。如果两者都失败,那么根据您定义数据的方式,您有一个字符串。

于 2008-08-05T08:02:01.087 回答