为什么直接扔的排序列表实现使用ThrowHelper呢? [英] Why does SortedList implementation use ThrowHelper instead of throwing directly?

查看:292
本文介绍了为什么直接扔的排序列表实现使用ThrowHelper呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反射告诉我,SortedList的使用ThrowHelper类,而不是扔直接扔,例如例外情况:

Reflector tells me that SortedList uses a ThrowHelper class to throw exceptions instead of throwing them directly, for example:

public TValue this[TKey key]
{
    get
    {
        int index = this.IndexOfKey(key);
        if (index >= 0)
            return this.values[index];
        ThrowHelper.ThrowKeyNotFoundException();
        return default(TValue);
    }

其中ThrowKeyNotFoundException什么都不做的不仅仅是:

where ThrowKeyNotFoundException does nothing more than just:

throw new KeyNotFoundException();

请注意如何,这需要达夫声明返回默认值(TValue),这是不可达。我必须得出结论,这是与利益大到足以证明这一模式。

Note how this requires a duff statement "return default(TValue)" which is unreachable. I must conclude that this is a pattern with benefits large enough to justify this.

这些是什么好处?

推荐答案

根据 ThrowHelper.cs 源代码的主要目的是降低即时编译代码大小。下面是从链接直接复制粘贴:

According to ThrowHelper.cs source code the main purpose is to reduce the JITted code size. Below is a direct copy paste from the link:

// This file defines an internal class used to throw exceptions in BCL code.
// The main purpose is to reduce code size. 
// 
// The old way to throw an exception generates quite a lot IL code and assembly code.
// Following is an example:
//     C# source
//          throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
//     IL code:
//          IL_0003:  ldstr      "key"
//          IL_0008:  ldstr      "ArgumentNull_Key"
//          IL_000d:  call       string System.Environment::GetResourceString(string)
//          IL_0012:  newobj     instance void System.ArgumentNullException::.ctor(string,string)
//          IL_0017:  throw
//    which is 21bytes in IL.
// 
// So we want to get rid of the ldstr and call to Environment.GetResource in IL.
// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
// argument name and resource name in a small integer. The source code will be changed to 
//    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
//
// The IL code will be 7 bytes.
//    IL_0008:  ldc.i4.4
//    IL_0009:  ldc.i4.4
//    IL_000a:  call       void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
//    IL_000f:  ldarg.0
//
// This will also reduce the Jitted code size a lot.

这篇关于为什么直接扔的排序列表实现使用ThrowHelper呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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