C# List vs IEnumerable performance question

后端 未结 4 2033
伪装坚强ぢ
伪装坚强ぢ 2021-02-12 14:55

Hi suppose these 2 methods:

private List GetProviderForType(Type type)
        {
            List returnValue = new         


        
4条回答
  •  滥情空心
    2021-02-12 15:17

    The precise answer to questions like this can vary depending on a lot of factors, and may change further as the CLR evolves. The only way to be sure is to measure it - and bear in mind that if the difference is small compared to the operation this will appear in, then you should pick the most readable, maintainable way of writing it.

    And on that note, you might also want to try:

    private IEnumerable GetProviderForType1(Type type)
    {
        return _objectProviders.Where(provider => 
                      provider.Key.IsAssignableFrom(type) ||
                      type.IsAssignableFrom(provider.Key)) &&
                      provider.Value.SupportsType(type))
                               .Select(p => p.Value);
    }
    

    You can also give yourself a lot of flexibility by returning IEnumerable and then using the ToList extension method if you want to "snapshot" the results into a list. This will avoid repeated evaluation of the code to generate the list, if you need to examine it multiple times.

提交回复
热议问题