C# 什么是最快的:(int)、Convert.ToInt32(x) 或 Int32.Parse(x)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/638496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is fastest: (int), Convert.ToInt32(x) or Int32.Parse(x)?
提问by Dan McClain
Which of the following code is fastest/best practice for converting some object x?
以下哪个代码是转换某些对象 x 的最快/最佳实践?
int myInt = (int)x;
or
或者
int myInt = Convert.ToInt32(x);
or
或者
int myInt = Int32.Parse(x);
or in the case of a string 's'
或者在字符串 's' 的情况下
int myInt;
Int32.TryParse(s, out myInt);
I'm curious on which performs the fastest for datatypes which have a method in Convert, not just ints. I just used int as an example.
我很好奇哪个对于在 Convert 中有方法的数据类型执行最快,而不仅仅是 ints。我只是以 int 为例。
Edit: This case arose from getting information back from a datatable. Will (int) still work the fastest?
编辑:这种情况源于从数据表中获取信息。(int) 仍然是最快的吗?
From some testing, when object x =123123123, int performs the fastest, like many have said. When x is a string, Parse runs the fastest (note: cast throws an exception). What I am really curious is how they run when the value is being retrieved in the following way:
从一些测试来看,当对象 x =123123123 时,int 执行速度最快,正如许多人所说。当 x 是字符串时,Parse 运行最快(注意:cast 抛出异常)。我真正好奇的是当以下列方式检索值时它们是如何运行的:
foreach(DataRow row in someTable.Rows)
{
myInt = (int)row["some int value"];
myInt2 = Int.Parse(row["some int value"]);
myInt2 = Convert.ToInt32(row["some int value"]);
}
采纳答案by demoncodemonkey
Why don't you just try it a couple of thousand times?
你为什么不试试几千次呢?
(this goes for all "What is fastest:" questions)
(这适用于所有“什么是最快的:”问题)
Hmmm, lots of downvotes over the years... I guess I should expand on this answer.
嗯,多年来很多反对票......我想我应该扩展这个答案。
The above statement was made with a degree of flippancy in my youth, however I still agree with its sentiment. It is not worthwhile spending time creating a SO question asking others what they think is faster out of two or three operations that take less than 1ms each.
上面的说法是在我年轻的时候做出了一定程度的轻率,但我仍然同意它的观点。花时间创建一个 SO 问题来询问其他人他们认为在两个或三个每个花费不到 1 毫秒的操作中哪个更快是不值得的。
The fact that one might take a cycle or two longer than the other will almost certainly be negligible in day-to-day usage. And if you ever notice a performance problem in your application when you are converting millions of objects to ints, that'sthe point where you can profile the actualcode, and you'll easily be able to test whether the int conversion is actually the bottleneck.
在日常使用中,一个周期可能比另一个周期长一两个周期的事实几乎可以忽略不计。如果您在将数百万个对象转换为 int 时注意到应用程序中的性能问题,那么您就可以分析实际代码,并且您将能够轻松测试 int 转换是否实际上是瓶颈。
And whereas today it's the object-int converter, tomorrow maybe you'll think your object-DateTime converter is taking a long time. Would you create another SO question to find out what's the fastest method?
而今天它是 object-int 转换器,明天也许您会认为您的 object-DateTime 转换器需要很长时间。您会创建另一个 SO 问题来找出最快的方法吗?
As for your situation (no doubt long since resolved by now), as mentioned in a comment, you are querying a database, so object-int conversion is the least of your worries. If I was you I would use any of the conversion methods you mentioned. If a problem arises I would isolate the call, using a profiler or logging. Then when I notice that object-int conversion is being done a million times and the total time taken by that conversion seems relatively high, I would change to using a different conversion method and re-profile. Pick the conversion method that takes the least time. You could even test this in a separate solution, or even LINQPad, or Powershell etc.
至于你的情况(毫无疑问,现在已经解决了),正如评论中提到的,你正在查询一个数据库,所以 object-int 转换是你最不担心的。如果我是你,我会使用你提到的任何转换方法。如果出现问题,我会使用分析器或日志来隔离调用。然后,当我注意到 object-int 转换进行了一百万次并且该转换所花费的总时间似乎相对较长时,我会改为使用不同的转换方法并重新配置文件。选择花费最少时间的转换方法。您甚至可以在单独的解决方案中进行测试,甚至可以在 LINQPad 或 Powershell 等中进行测试。
回答by Surgical Coder
Best practice would be TryParse, and seeing the result of that, if it worked - otherwise you could get exceptions
最佳实践是 TryParse,并查看结果,如果它有效 - 否则您可能会遇到异常
回答by dr. evil
If you know that the data is definitely int then int myInt = (int)x;
should be the fastest option. Otherwise TryParse
will help you to get it right without the slowness of exceptions.
如果您知道数据绝对是 int 那么int myInt = (int)x;
应该是最快的选择。否则TryParse
将帮助您正确处理,而不会出现异常缓慢的情况。
BTW :
顺便提一句 :
(int) only unboxes therefore faster,
(int) 只有这样才能更快地拆箱,
(int) IL =
(int) IL =
.locals init (
[0] object x,
[1] int32 Y)
L_0000: ldc.i4.1
L_0001: box int32
L_0006: stloc.0
L_0007: ldloc.0
L_0008: unbox int32
L_000d: ldobj int32
L_0012: stloc.1
L_0013: ret
Convert.Toint32=
转换.Toint32=
.locals init (
[0] object x,
[1] int32 Y)
L_0000: ldc.i4.1
L_0001: box int32
L_0006: stloc.0
L_0007: ldloc.0
L_0008: call object [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::GetObjectValue(object)
L_000d: call int32 [mscorlib]System.Convert::ToInt32(object)
L_0012: stloc.1
L_0013: ret
回答by GateKiller
In the end, they all end up calling:
最后,他们都打来电话:
System.Number.ParseInt32(string s, NumberStyles style, NumberFormatInfo info);
So in summary, there will be no difference what so ever.
所以总而言之,不会有什么区别。
Have a look in .Net Reflectorto see this.
看看.Net Reflector看看这个。
回答by Matthias Meid
Not sure about performance, but these methods aren't the same at all. Both Parse
and TryParse
work with string, the String
representation of an object is parsed (see MSDN).
不确定性能,但这些方法根本不一样。二者Parse
并TryParse
用绳子工作中,String
一个对象的表示被解析(参见MSDN)。
Converts the string representation of a number to its 32-bit signed integer equivalent.
将数字的字符串表示形式转换为其等效的 32 位有符号整数。
Not sure about casting and the Convert
class, but cast is only for objects that are already integers in fact but not strongly typed.
不确定转换和Convert
类,但转换仅适用于实际上已经是整数但不是强类型的对象。
Matthias
马蒂亚斯
回答by Joel Coehoorn
Fastest != Best Practice!
最快!= 最佳实践!
For example, (int)
is almost certainly the fastest because it's an operator rather than a function call, but it will only work in certain situations.
例如,(int)
几乎可以肯定是最快的,因为它是一个运算符而不是函数调用,但它只在某些情况下有效。
The best practice is to use the most readablecode that won't negatively impact your performance, and 99 times out of 100 an integer conversion isn't driving your app's performance. If it is, use the most appropriate, narrowest conversion you can. Sometimes that's (int)
. Sometimes it's TryParse()
. Sometimes it's Convert.ToInt32()
.
最佳做法是使用不会对您的性能产生负面影响的可读性最强的代码,100 次中有 99 次整数转换不会提高应用程序的性能。如果是,请尽可能使用最合适、最窄的转换。有时就是这样(int)
。有时是TryParse()
。有时是Convert.ToInt32()
。
回答by dan-gph
If you had the need for the extra speed, it would be easy to test the different the different options. Since you aren't testing them, you mustn't need them. Don't waste your time with pointless micro-optimizations!
如果您需要额外的速度,可以很容易地测试不同的选项。由于您没有测试它们,因此您一定不需要它们。不要在毫无意义的微优化上浪费时间!
回答by Keith
It depends on what you expect x to be
这取决于你期望 x 是什么
If x is a boxed int then (int)x
is quickest.
如果 x 是一个装箱的 int 那么(int)x
最快。
If x is a string but is definitely a valid number then int.Parse(x)
is best
如果 x 是一个字符串但绝对是一个有效的数字,那么int.Parse(x)
最好
If x is a string but it might not be valid then int.TryParse(x)
is far quicker than a try-catch block.
如果 x 是一个字符串但它可能无效,那么int.TryParse(x)
它比 try-catch 块要快得多。
The difference between Parse and TryParse is negligible in all but the very largest loops.
Parse 和 TryParse 之间的差异在除最大循环之外的所有循环中都可以忽略不计。
If you don't know what x is (maybe a string or a boxed int) then Convert.ToInt32(x)
is best.
如果您不知道 x 是什么(可能是字符串或装箱整数),那么Convert.ToInt32(x)
最好。
These generalised rules are also true for all value types with static Parse and TryParse methods.
这些通用规则也适用于所有具有静态 Parse 和 TryParse 方法的值类型。
回答by nothrow
(int) conversion on string won't work, so I dont test it. Convert.ToInt32 reflects as testing the value to null and THEN calling int.Parse, so should in general tend to be slower than int.Parse().
(int) 字符串转换不起作用,所以我不测试它。Convert.ToInt32 反映为将值测试为 null,然后调用 int.Parse,因此通常应该比 int.Parse() 慢。
回答by fractos
When optimising a bound data grid in .Net 2, I found almost half the time was spent in various object's ToString() methods that were then used as the inputs of Convert operations. By isolating these cases and by casting to the correct type where possible (since they were rows taken out of a database and the types could be relied upon) this caused a massive increase in speed of that data binding operation.
在 .Net 2 中优化绑定数据网格时,我发现几乎一半的时间都花在了各种对象的 ToString() 方法上,然后将这些方法用作 Convert 操作的输入。通过隔离这些情况并在可能的情况下强制转换为正确的类型(因为它们是从数据库中取出的行并且可以依赖类型),这导致该数据绑定操作的速度大幅提高。
So, if you know the type of the thing up front and you'll hit the piece of code enough times, it's worth the effort to cast it directly instead of converting where necessary.
因此,如果您预先知道事物的类型并且您会多次命中该段代码,那么直接转换它而不是在必要时进行转换是值得的。