相关疑难解决方法(0)

在LINQ查询中调用ToList()或ToArray()会更好吗?

我经常遇到我想在我声明它的地方评估查询的情况.这通常是因为我需要多次迭代它并且计算起来很昂贵.例如:

string raw = "...";
var lines = (from l in raw.Split('\n')
             let ll = l.Trim()
             where !string.IsNullOrEmpty(ll)
             select ll).ToList();
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,如果我不打算修改结果,那么我不妨打电话给ToArray()而不是ToList().

我想知道是否ToArray()通过第一次调用实现,ToList()因此内存效率低于仅调用ToList().

我疯了吗?我应该只是打电话ToArray()- 安全且安全地知道内存不会被分配两次吗?

.net linq performance

488
推荐指数
15
解决办法
8万
查看次数

C#:ToArray表现

背景:

我承认我并没有尝试对此进行基准测试,但我很好奇......

Enumerable.ToArray<T>(和它的堂兄Enumerable.ToList<T>)的CPU /内存特性是什么?

既然IEnumerable不预先通告它有多少元素,我(可能是天真地)假定ToArray必须"猜测"一个初始数组大小,然后如果第一个猜测看起来太小则重新调整/重新分配数组,然后调整大小如果第二次猜测看起来太小等等,它又会再次出现......这会产生比线性更差的性能.

我可以想象更好的方法涉及(混合)列表,但这仍然需要多个分配(虽然不是重新分配)和相当多的复制,尽管它可能是线性整体尽管开销.

题:

幕后是否有任何"神奇"发生,避免了重复调整大小的需要,并ToArray在空间和时间上呈线性?

更一般地说,是否有关于BCL性能特征的"官方"文档?

.net c# linq performance

13
推荐指数
2
解决办法
7175
查看次数

响应类中的IEnumerable vs List,ServiceStack

我不确定这是不是问题.

如果我在这里使用List,它在root/xml/metadata中都有效吗?op =竞赛和root/Competitions

[DataContract]
public class CompetitionsResponse : IHasResponseStatus
{
    [DataMember]

    public List<Competitions> Competitions { get; set; }

    //Auto inject and serialize web service exceptions
    [DataMember]
    public ResponseStatus ResponseStatus { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

HTTP/1.1 200 OK Content-Type:application/xml Content-Length:length

<CompetitionsResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/FSI.API.ServiceModel">
  <Competitions>
    <Competitions>
      <CompName>String</CompName>
      <CompType>String</CompType>
      <CompetitionID>0</CompetitionID>
    </Competitions>
  </Competitions>
  <ResponseStatus xmlns:d2p1="http://schemas.servicestack.net/types">
    <d2p1:ErrorCode>String</d2p1:ErrorCode>
    <d2p1:Errors>
      <d2p1:ResponseError>
        <d2p1:ErrorCode>String</d2p1:ErrorCode>
        <d2p1:FieldName>String</d2p1:FieldName>
        <d2p1:Message>String</d2p1:Message>
      </d2p1:ResponseError>
    </d2p1:Errors>
    <d2p1:Message>String</d2p1:Message>
    <d2p1:StackTrace>String</d2p1:StackTrace>
  </ResponseStatus>
</CompetitionsResponse>
Run Code Online (Sandbox Code Playgroud)

但如果我使用"IEnumerable"

[DataContract]
public class CompetitionsResponse : IHasResponseStatus
{
    [DataMember]
    public IEnumerable<Competitions> Competitions { get; set; }

    //Auto …
Run Code Online (Sandbox Code Playgroud)

c# servicestack

5
推荐指数
1
解决办法
1397
查看次数

标签 统计

.net ×2

c# ×2

linq ×2

performance ×2

servicestack ×1