C# .First() 与 [0]

2024-02-27

有兴趣,做法有什么不同吗?
所以,我创建了两个片段。

Snippet A 
List<int> a = new List<int>();
a.Add(4);
a.Add(6);
int b = a.First(); 

and

Snippet B 
List<int> a = new List<int>();
a.Add(4);
a.Add(6);
int b = a[0]; 

我们信任 IL,所以

Snippet A IL
IL_0000:  nop         
IL_0001:  newobj      System.Collections.Generic.List<System.Int32>..ctor
IL_0006:  stloc.0     // a
IL_0007:  ldloc.0     // a
IL_0008:  ldc.i4.4    
IL_0009:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_000E:  nop         
IL_000F:  ldloc.0     // a
IL_0010:  ldc.i4.6    
IL_0011:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_0016:  nop         
IL_0017:  ldloc.0     // a
IL_0018:  call        System.Linq.Enumerable.First
IL_001D:  stloc.1     // b
IL_001E:  ret        

and

Snippet B IL
IL_0000:  nop         
IL_0001:  newobj      System.Collections.Generic.List<System.Int32>..ctor
IL_0006:  stloc.0     // a
IL_0007:  ldloc.0     // a
IL_0008:  ldc.i4.4    
IL_0009:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_000E:  nop         
IL_000F:  ldloc.0     // a
IL_0010:  ldc.i4.6    
IL_0011:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_0016:  nop         
IL_0017:  ldloc.0     // a
IL_0018:  ldc.i4.0    
IL_0019:  callvirt    System.Collections.Generic.List<System.Int32>.get_Item
IL_001E:  stloc.1     // b
IL_001F:  ret  

片段 B 产生了一个命令更多的 IL,但最终哪种方法更快呢?


你可以自己检查一下:

    static void Main()
    {
        List<long> resultsFirst = new List<long>();
        List<long> resultsIndex = new List<long>();

        Stopwatch s = new Stopwatch();

        for (int z = 0; z < 100; z++)
        {
            List<int>[] lists = new List<int>[10000];

            int temp = 0;

            for (int i = 0; i < lists.Length; i++)
                lists[i] = new List<int>() { 4, 6 };                

            s.Restart();

            for (int i = 0; i < lists.Length; i++)
                temp = lists[i].First();

            s.Stop();

            resultsFirst.Add(s.ElapsedTicks);

            s.Restart();

            for (int i = 0; i < lists.Length; i++)
                temp = lists[i][0];

            s.Stop();

            resultsIndex.Add(s.ElapsedTicks);
        }

        Console.WriteLine("LINQ First()  :   " + resultsFirst.Average());
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("By index      :   " + resultsIndex.Average());

        Console.ReadKey();
    }

释放模式下的输出:

LINQ 首先():367

按指数:84

调试模式下的输出:

LINQ 首先():401

按指数:177

P.S.

First方法的源代码为:

public static TSource First<TSource>(this IEnumerable<TSource> source)
{
    IList<TSource> list = source as IList<TSource>;
    if (list != null)
    {
        if (list.Count > 0)
        {
            return list[0];
        }
    }
    else
    {
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                return enumerator.Current;
            }
        }
    }
}

铸造作业source as IList<TSource>或者创建一个 Enumerator 对象很可能是原因First()速度要慢得多。

P.S.

考虑到这一点,我不建议总是使用索引器,因为它有时可能会产生可读性较差的代码。通常可读性比微观优化更重要。

例如:

var lastEmployee = employees[employees.Count - 1]; // and even
var lastEmployee = employees[^1];                  // C#8

可读性低于:

var lastEmployee = employees.Last();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# .First() 与 [0] 的相关文章

随机推荐

  • 为什么这个程序在 Python 中比 Objective-C 更快?

    我感兴趣了这个小例子 https stackoverflow com questions 5523058 how to optimize this python code from thinkpython exercise 10 10 55
  • 在 Safari 中提交表单时加载 GIF 会停止动画

    看看这个简单的JSFiddle http jsfiddle net VpDUG 4952 忽略所有的javascript代码 这里的问题只是关于动画加载GIF 我想在提交表单之前显示动画加载 GIF 我试过这个 setTimeout fun
  • 如何覆盖 .bash_aliases 中设置的别名

    我喜欢使用 bash 别名来自定义 bash 命令 有没有办法覆盖 bash 别名设置 或者我应该将别名重命名为与原始命令不同的名称 例如 我的 bash aliases 包括 alias ls ls ltr 如果我只想检索文件名 是否需要
  • 如何使用 bash 大括号扩展制作乘法表?到目前为止我有这个: echo $[{1..10}*{1..10}]

    我想更深入地学习 bash 所以我决定制作一个乘法表 我有以下声明的功能 echo 1 10 1 10 但这给了我以下输出 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15
  • 为初学者覆盖 Magento 管理控制器

    在 Magento 管理部分 我想覆盖核心 Mage 的 Sales Order ShipmentController php 控制器文件 我尝试使用 from 和 to 标签重写URL 但没有成功 我不知道这样做的实际和正确方法是什么 因
  • 在Delphi中,如何让货币数据类型以不同的形式以不同的货币显示?

    我需要编写一个 Delphi 应用程序 从数据库中的各个表中提取条目 并且不同的条目将采用不同的货币 因此 我需要根据我加载的项目的货币 为每种货币数据类型 英镑 欧元等 显示不同的小数位数和不同的货币字符 有没有一种方法可以几乎全局地更改
  • XSLT 具有相同匹配的多个模板

    我目前坚持应用多个 xsl template 来对元素进行相同的匹配 下面的例子显示了这个问题 有谁知道使用两个 模板匹配 创建预期输出的 XSL 模板吗 由于技术原因 不可能将两个 模板 元素放在一起 Input
  • 提高线程速度[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 每次调用线程后 其速度都会增加 特别是 FirstCircleRepaintThread SecoundCircleRepaintThre
  • 声明函数之前的“new”运算符

    就像探索 javascript 作为我对整个编程的第一次参考 但由于我不是专业人士 无法理解很多东西 因此 如果有人能够解释幕后实际发生的事情 我们将不胜感激 在 body 标签中 我声明了两个函数 一个带有 new 另一个没有 新函数 s
  • 将字符串乘以数字

    我想在 PHP 中显示分数 为此我写道 a 3 b 2 c a b echo c this displays 3 2 but on the other hand I want to multiply c by an integer echo
  • Cheerio、axios、reactjs 从网页上抓取表格并返回空列表

    试图从这个网站上删除这张表 https www investing com commodities real time futures https www investing com commodities real time future
  • PHP 文档根目录

    只是为了确认 正在使用 SERVER DOCUMENT ROOT 与使用相同 in HTML 例如 如果当前文档是 folder folder folder index php 我可以使用 在 HTML 中 从根开始 somedoc htm
  • 如何将参与者消息限制为特定类型?

    In Akka http akka io 除了使用 RPC 风格编程模型的 Typed Actor API 之外 是否有其他方法可以将发送给 Actor 的消息限制为特定的静态类型 我可以在 Akka 中使用消息传递风格而不放弃 Actor
  • 在 Liferay 中控制 Portlet 的大小

    我有一个简单的 Vaadin portlet 它显示嵌入式页面 例如 www stackoverflow com 在 Liferay 中 我将 portlet 所在的页面布局设置为 1 列布局 以便 portlet 填满整个页面 现在 如果
  • 查找美国城市所在的美国县的最佳方式是什么?

    我正在寻找最好 最简单的方法来以编程方式获取美国特定城市所在的美国县的名称 似乎没有一个简单的 API 可用于此类 看似简单 的任务 您可以免费下载一个包含县 市 邮政编码信息的数据库 例如 http www unitedstateszip
  • 对带有 html 实体的文本框执行 jQuery val()

    我已经使用简单的 js 小提琴设置了我的问题http jsfiddle net um788f6q http jsfiddle net um788f6q
  • 为什么Spring的PathMatchingResourcePatternResolver不匹配“*”什么都没有?

    我正在尝试从 zip 文件中获取属性文件 我需要使用通配符 因为我想要匹配 my properties 或 my en properties 我创建一个ResourcePatternResolver像这样 ClassLoader loade
  • JavaFX css 类样式

    如何为扩展 JavaFX 对象的类设置 CSS 样式 public class DiagramPane extends ScrollPane implements IDiagramEditor Methods go here 我在main方
  • 何时使用上下文处理器

    我有一个网站 其中包含一个 userBox 其中显示每个登录用户的一些数据 您的姓名 头像等 从我对 django 的了解来看 很明显 我应该将用户查询添加到上下文处理器 以便我可以使用 user 其中的变量包括 userBox 但是在使用
  • C# .First() 与 [0]

    有兴趣 做法有什么不同吗 所以 我创建了两个片段 Snippet A List