“as”带来的性能惊喜和可为 null 的类型
我只是在深入修改 C# 的第 4 章,其中涉及可为 null 的类型,并且我添加了有关使用“as”运算符的部分,它允许您编写:
object o = ...;
int? x = o as int?;
if (x.HasValue)
{
... // Use x.Value in here
}
我认为这确实很简洁,并且可以改进性能优于 C# 1 等效项,使用“is”后跟强制转换 - 毕竟,这样我们只需要请求一次动态类型检查,然后进行简单的值检查。
然而,情况似乎并非如此。我在下面提供了一个示例测试应用程序,它基本上对对象数组中的所有整数求和 - 但该数组包含大量空引用和字符串引用以及装箱整数。该基准测试测量您必须在 C# 1 中使用的代码、使用“as”运算符的代码,以及只是为了启动 LINQ 解决方案。令我惊讶的是,在这种情况下,C# 1 代码快了 20 倍 - 甚至 LINQ 代码(考虑到涉及迭代器,我预计会更慢)也击败了“as”代码。
可空类型的 isinst
的 .NET 实现真的很慢吗?是否是额外的 unbox.any
导致了问题?对此还有其他解释吗?目前感觉我必须包含一个警告,反对在性能敏感的情况下使用它......
结果:
演员阵容:10000000 : 121
如:10000000:2211
LINQ:10000000:2143
代码:
using System;
using System.Diagnostics;
using System.Linq;
class Test
{
const int Size = 30000000;
static void Main()
{
object[] values = new object[Size];
for (int i = 0; i < Size - 2; i += 3)
{
values[i] = null;
values[i+1] = "";
values[i+2] = 1;
}
FindSumWithCast(values);
FindSumWithAs(values);
FindSumWithLinq(values);
}
static void FindSumWithCast(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = 0;
foreach (object o in values)
{
if (o is int)
{
int x = (int) o;
sum += x;
}
}
sw.Stop();
Console.WriteLine("Cast: {0} : {1}", sum,
(long) sw.ElapsedMilliseconds);
}
static void FindSumWithAs(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = 0;
foreach (object o in values)
{
int? x = o as int?;
if (x.HasValue)
{
sum += x.Value;
}
}
sw.Stop();
Console.WriteLine("As: {0} : {1}", sum,
(long) sw.ElapsedMilliseconds);
}
static void FindSumWithLinq(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = values.OfType<int>().Sum();
sw.Stop();
Console.WriteLine("LINQ: {0} : {1}", sum,
(long) sw.ElapsedMilliseconds);
}
}
I'm just revising chapter 4 of C# in Depth which deals with nullable types, and I'm adding a section about using the "as" operator, which allows you to write:
object o = ...;
int? x = o as int?;
if (x.HasValue)
{
... // Use x.Value in here
}
I thought this was really neat, and that it could improve performance over the C# 1 equivalent, using "is" followed by a cast - after all, this way we only need to ask for dynamic type checking once, and then a simple value check.
This appears not to be the case, however. I've included a sample test app below, which basically sums all the integers within an object array - but the array contains a lot of null references and string references as well as boxed integers. The benchmark measures the code you'd have to use in C# 1, the code using the "as" operator, and just for kicks a LINQ solution. To my astonishment, the C# 1 code is 20 times faster in this case - and even the LINQ code (which I'd have expected to be slower, given the iterators involved) beats the "as" code.
Is the .NET implementation of isinst
for nullable types just really slow? Is it the additional unbox.any
that causes the problem? Is there another explanation for this? At the moment it feels like I'm going to have to include a warning against using this in performance sensitive situations...
Results:
Cast: 10000000 : 121
As: 10000000 : 2211
LINQ: 10000000 : 2143
Code:
using System;
using System.Diagnostics;
using System.Linq;
class Test
{
const int Size = 30000000;
static void Main()
{
object[] values = new object[Size];
for (int i = 0; i < Size - 2; i += 3)
{
values[i] = null;
values[i+1] = "";
values[i+2] = 1;
}
FindSumWithCast(values);
FindSumWithAs(values);
FindSumWithLinq(values);
}
static void FindSumWithCast(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = 0;
foreach (object o in values)
{
if (o is int)
{
int x = (int) o;
sum += x;
}
}
sw.Stop();
Console.WriteLine("Cast: {0} : {1}", sum,
(long) sw.ElapsedMilliseconds);
}
static void FindSumWithAs(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = 0;
foreach (object o in values)
{
int? x = o as int?;
if (x.HasValue)
{
sum += x.Value;
}
}
sw.Stop();
Console.WriteLine("As: {0} : {1}", sum,
(long) sw.ElapsedMilliseconds);
}
static void FindSumWithLinq(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = values.OfType<int>().Sum();
sw.Stop();
Console.WriteLine("LINQ: {0} : {1}", sum,
(long) sw.ElapsedMilliseconds);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
显然,JIT 编译器可以为第一种情况生成的机器代码效率更高。一条真正有帮助的规则是,只能将对象拆箱为与装箱值具有相同类型的变量。这使得 JIT 编译器能够生成非常高效的代码,无需考虑值转换。
is 运算符测试很简单,只需检查对象是否不为 null 并且是否为预期类型,只需一些机器代码指令。转换也很容易,JIT 编译器知道对象中值位的位置并直接使用它们。不会发生复制或转换,所有机器代码都是内联的,并且只需要大约十几个指令。在 .NET 1.0 中,当拳击很常见时,这需要非常高效。
转换为 int?需要更多的工作。装箱整数的值表示与
Nullable
的内存布局不兼容。需要进行转换,并且由于可能的装箱枚举类型,代码很棘手。 JIT 编译器生成对名为 JIT_Unbox_Nullable 的 CLR 辅助函数的调用来完成工作。这是适用于任何值类型的通用函数,其中有很多代码用于检查类型。并且该值被复制。由于此代码被锁定在 mscorwks.dll 内,因此很难估计成本,但可能有数百条机器代码指令。Linq OfType() 扩展方法还使用 is 运算符和强制转换。然而,这是对泛型类型的强制转换。 JIT 编译器生成对辅助函数 JIT_Unbox() 的调用,该函数可以执行到任意值类型的转换。我没有很好的解释为什么它像转换为 Nullable一样慢,因为应该需要更少的工作。我怀疑 ngen.exe 可能会在这里造成麻烦。
Clearly the machine code the JIT compiler can generate for the first case is much more efficient. One rule that really helps there is that an object can only be unboxed to a variable that has the same type as the boxed value. That allows the JIT compiler to generate very efficient code, no value conversions have to be considered.
The is operator test is easy, just check if the object isn't null and is of the expected type, takes but a few machine code instructions. The cast is also easy, the JIT compiler knows the location of the value bits in the object and uses them directly. No copying or conversion occurs, all machine code is inline and takes but about a dozen instructions. This needed to be really efficient back in .NET 1.0 when boxing was common.
Casting to int? takes a lot more work. The value representation of the boxed integer is not compatible with the memory layout of
Nullable<int>
. A conversion is required and the code is tricky due to possible boxed enum types. The JIT compiler generates a call to a CLR helper function named JIT_Unbox_Nullable to get the job done. This is a general purpose function for any value type, lots of code there to check types. And the value is copied. Hard to estimate the cost since this code is locked up inside mscorwks.dll, but hundreds of machine code instructions is likely.The Linq OfType() extension method also uses the is operator and the cast. This is however a cast to a generic type. The JIT compiler generates a call to a helper function, JIT_Unbox() that can perform a cast to an arbitrary value type. I don't have a great explanation why it is as slow as the cast to
Nullable<int>
, given that less work ought to be necessary. I suspect that ngen.exe might cause trouble here.在我看来,isinst 对于可空类型来说确实很慢。在方法 FindSumWithCast 中,我更改
为该
方法,这也显着减慢了执行速度。我能看到的 IL 中唯一的区别是它
被更改为
It seems to me that the
isinst
is just really slow on nullable types. In methodFindSumWithCast
I changedto
which also significantly slows down execution. The only differenc in IL I can see is that
gets changed to
这最初是作为对 Hans Passant 优秀答案的评论,但它太长了,所以我想在这里添加一些内容:
首先,C#
as
运算符将发出isinst IL 指令(
is
运算符也是如此)。 (另一个有趣的指令是castclass
,当您进行直接转换并且编译器知道不能省略运行时检查时发出。)这是
isinst
的作用(ECMA 335 分区 III, 4.6):最重要的是:
因此,性能在这种情况下,killer 不是
isinst
,而是附加的unbox.any
。汉斯的回答并不清楚这一点,因为他只查看了 JIT 代码。一般来说,C# 编译器会在isinst T?
之后发出unbox.any
(但如果您执行isinst T
,则会忽略它,当T
是引用类型时)。为什么要这样做?
isinst T?
永远不会产生明显的效果,即您返回一个T?
。相反,所有这些说明确保您拥有一个可以拆箱为T?
的“装箱 T”
。要获得实际的T?
,我们仍然需要将"boxed T"
拆箱为T?
,这就是编译器发出T?
的原因isinst
之后的代码>unbox.any。如果您考虑一下,这是有道理的,因为T?
的“盒格式”只是一个“盒装 T”
并使得castclass
和isinst
执行拆箱会不一致。使用标准<中的一些信息来支持汉斯的发现/a>,这里是:
(ECMA 335 Partition III,4.33):
unbox.any
(ECMA 335 分区 III,4.32):
拆箱
This originally started out as a Comment to Hans Passant's excellent answer, but it got too long so I want to add a few bits here:
First, the C#
as
operator will emit anisinst
IL instruction (so does theis
operator). (Another interesting instruction iscastclass
, emited when you do a direct cast and the compiler knows that runtime checking cannot be ommited.)Here is what
isinst
does (ECMA 335 Partition III, 4.6):Most importantly:
So, the performance killer isn't
isinst
in this case, but the additionalunbox.any
. This wasn't clear from Hans' answer, as he looked at the JITed code only. In general, the C# compiler will emit anunbox.any
after aisinst T?
(but will omit it in case you doisinst T
, whenT
is a reference type).Why does it do that?
isinst T?
never has the effect that would have been obvious, i.e. you get back aT?
. Instead, all these instructions ensure is that you have a"boxed T"
that can be unboxed toT?
. To get an actualT?
, we still need to unbox our"boxed T"
toT?
, which is why the compiler emits anunbox.any
afterisinst
. If you think about it, this makes sense because the "box format" forT?
is just a"boxed T"
and makingcastclass
andisinst
perform the unbox would be inconsistent.Backing up Hans' finding with some information from the standard, here it goes:
(ECMA 335 Partition III, 4.33):
unbox.any
(ECMA 335 Partition III, 4.32):
unbox
有趣的是,我通过
dynamic
传递了有关运算符支持的反馈,对于Nullable
来说,速度要慢一个数量级(类似于 这个早期测试) - 我怀疑出于非常相似的原因。一定喜欢
Nullable
。另一个有趣的地方是,即使 JIT 发现(并删除)不可为空结构的null
,它也会为Nullable
删除它:Interestingly, I passed on feedback about operator support via
dynamic
being an order-of-magnitude slower forNullable<T>
(similar to this early test) - I suspect for very similar reasons.Gotta love
Nullable<T>
. Another fun one is that even though the JIT spots (and removes)null
for non-nullable structs, it borks it forNullable<T>
:为了使这个答案保持最新,值得一提的是,此页面上的大部分讨论现在对于 C# 7.1 和 .NET 4.7 来说已经没有意义了。支持精简语法,也能生成最佳的 IL 代码。
OP 的原始示例...
变得简单...
我发现新语法的一个常见用途是当您编写 .NET 值类型(即
struct
在C#中)实现了IEquatable
(大多数人应该这样做)。实现强类型Equals(MyStruct other)
方法后,您现在可以优雅地重定向非类型化Equals(Object obj)
重写(继承自Object) 如下:
附录:此处给出了此答案中上面显示的前两个示例函数(分别)的
Release
构建IL代码。虽然新语法的 IL 代码确实小了 1 个字节,但它主要是通过零次调用(相对于两次)并在可能的情况下完全避免unbox
操作来赢得巨大胜利。如需进一步测试以证实我关于新 C#7 语法的性能超越以前可用选项的评论,请参阅 此处(特别是示例“D”)。
In order to keep this answer up-to-date, it's worth mentioning that the most of the discussion on this page is now moot now with C# 7.1 and .NET 4.7 which supports a slim syntax that also produces the best IL code.
The OP's original example...
becomes simply...
I have found that one common use for the new syntax is when you are writing a .NET value type (i.e.
struct
in C#) that implementsIEquatable<MyStruct>
(as most should). After implementing the strongly-typedEquals(MyStruct other)
method, you can now gracefully redirect the untypedEquals(Object obj)
override (inherited fromObject
) to it as follows:Appendix: The
Release
build IL code for the first two example functions shown above in this answer (respectively) are given here. While the IL code for the new syntax is indeed 1 byte smaller, it mostly wins big by making zero calls (vs. two) and avoiding theunbox
operation altogether when possible.For further testing which substantiates my remark about the performance of the new C#7 syntax surpassing the previously available options, see here (in particular, example 'D').
这是上面 FindSumWithAsAndHas 的结果:
这是 FindSumWithCast 的结果:
结果:
使用
as
,它首先测试一个对象是否是 Int32 的实例;它在底层使用 isinst Int32 (类似于手写代码: if (o is int) )。并且使用as
,它也无条件地拆箱该对象。调用属性是真正的性能杀手(它仍然是底层的函数),IL_0027使用强制转换,首先测试对象是否是
int
if (o is int)
;在幕后,这是使用isinst Int32
。如果它是 int 的实例,那么您可以安全地拆箱该值,IL_002D简单地说,这是使用
as
方法的伪代码:这是使用强制转换方法的伪代码:
所以强制转换(
(int)a[i]
,好吧,语法看起来像强制转换,但实际上是拆箱,强制转换和拆箱共享相同的语法,下次我会迂腐地用右边的terminology) 方法确实更快,当对象明确是 int 时,您只需要取消装箱值。使用as
方法却不能说同样的事情。This is the result of FindSumWithAsAndHas above:
This is the result of FindSumWithCast:
Findings:
Using
as
, it test first if an object is an instance of Int32; under the hood it is usingisinst Int32
(which is similar to hand-written code: if (o is int) ). And usingas
, it also unconditionally unbox the object. And it's a real performance-killer to call a property(it's still a function under the hood), IL_0027Using cast, you test first if object is an
int
if (o is int)
; under the hood this is usingisinst Int32
. If it is an instance of int, then you can safely unbox the value, IL_002DSimply put, this is the pseudo-code of using
as
approach:And this is the pseudo-code of using cast approach:
So the cast (
(int)a[i]
, well the syntax looks like a cast, but it's actually unboxing, cast and unboxing share the same syntax, next time I'll be pedantic with the right terminology) approach is really faster, you only needed to unbox a value when an object is decidedly anint
. The same thing can't be said to using anas
approach.进一步分析:
输出:
我们可以从这些数字中推断出什么?
实施^_^
Profiling further:
Output:
What can we infer from these figures?
implementation ^_^
我没有时间尝试它,但您可能想要:
因为
您每次都创建一个新对象,这不会完全解释问题,但可能有所贡献。
I don't have time to try it, but you may want to have:
as
You are creating a new object each time, which won't completely explain the problem, but may contribute.
我尝试了精确的类型检查构造
typeof(int) == item.GetType()
,它的执行速度与item is int
版本一样快,并且始终返回数字 (强调:即使您向数组写入了Nullable
,您也需要使用typeof(int)
)。您还需要在此处进行额外的null != item
检查。然而,
typeof(int?) == item.GetType()
保持快速(与item is int?
相比),但总是返回 false。在我看来,typeof-construct 是进行精确类型检查的最快方法,因为它使用 RuntimeTypeHandle。由于本例中的确切类型与 nullable 不匹配,我的猜测是,is/as 必须在此处进行额外的繁重工作,以确保它实际上是 Nullable 类型的实例。
老实说:你的
is Nullable是什么?再加上HasValue
买你的?没有什么。您始终可以直接转到底层(值)类型(在本例中)。您要么获得该值,要么“不,不是您所要求的类型的实例”。即使您将(int?)null
写入数组,类型检查也会返回 false。I tried the exact type check construct
typeof(int) == item.GetType()
, which performs as fast as theitem is int
version, and always returns the number (emphasis: even if you wrote aNullable<int>
to the array, you would need to usetypeof(int)
). You also need an additionalnull != item
check here.However
typeof(int?) == item.GetType()
stays fast (in contrast toitem is int?
), but always returns false.The typeof-construct is in my eyes the fastest way for exact type checking, as it uses the RuntimeTypeHandle. Since the exact types in this case don't match with nullable, my guess is,
is/as
have to do additional heavylifting here on ensuring that it is in fact an instance of a Nullable type.And honestly: what does your
is Nullable<xxx> plus HasValue
buy you? Nothing. You can always go directly to the underlying (value) type (in this case). You either get the value or "no, not an instance of the type you were asking for". Even if you wrote(int?)null
to the array, the type check will return false.输出:
[编辑:2010-06-19]
注意:之前的测试是在VS内部完成的,配置调试,使用VS2009,使用Core i7(公司开发机)。
以下是在我的机器上使用 Core 2 Duo、使用 VS2010 完成的
Outputs:
[EDIT: 2010-06-19]
Note: Previous test was done inside VS, configuration debug, using VS2009, using Core i7(company development machine).
The following was done on my machine using Core 2 Duo, using VS2010