按名称或类型比较更快?
进行对象比较时,按名称(字符串)比较还是按类型(指针)比较更快?
请参见下文:
if(sender is DataGridView) { .. }
或
if(sender.GetType().ToString() == "System.Forms.DataGridView") { .. }
When performing an object comparison, is it faster to compare by name (string) or type (pointer)?
See below:
if(sender is DataGridView) { .. }
or
if(sender.GetType().ToString() == "System.Forms.DataGridView") { .. }
Note: I may not have the syntax exactly right... this is a C# example, but the comment answer here in one my questions made me think about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两者并不等同。仅当发送者的类型恰好是
DataGridView
时,第二个才会匹配。如果类型是 DataGridView 或继承自 DataGridView,则第一个将被匹配。所以第一点,比较并不相同。正如 Benjamin Podszun 在他的回答中所说,精确类型相等的正确比较是:除此之外,我的直觉是,如果类型完全是
DataGridView
,类型比较肯定会更快,但它会如果它是后代类型,则不太明确。The two aren't equivalent. The second will only be matched if the type of sender is exactly
DataGridView
. The first will be matched if the type is, or inherits from,DataGridView
. So point one, the comparisons are not the same. As Benjamin Podszun says in his answer, the correct comparison for exact type equality is:That aside, my gut feeling is that type comparison will be faster for sure if the type is exactly
DataGridView
, but that it will be less clear cut in the case where it is a descendant type.都应该更好。
无论性能特征是什么,
should probably better be
whatever the performance characteristics might be.