新的object [] {}与Array.Empty< object>() [英] new object[] {} vs Array.Empty<object>()

查看:82
本文介绍了新的object [] {}与Array.Empty< object>()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我键入以下代码时:

object[] objects = new object[] { };

Visual Studio告诉我:

Visual Studio tells me:

避免不必要的零长度分配.使用Array.Empty() 代替.

Avoid unnecessary zero-length allocations. Use Array.Empty() instead.

使用一个在另一个之上有什么实际含义吗?

Are there any actual implications of using one over the other?

发出警告的原因是什么?

What is the reason for the warning?

推荐答案

您正在创建一个空数组.由于您无法更改数组实例的容量,因此该字段始终为空(听起来很奇怪,您不能更改其长度 length ,我不知道为什么).每次执行此操作时,都会创建一个永远无法使用的数组实例.大量执行此操作可能会浪费GC和内存压力,从而导致警告.

You're creating an empty array. Which will always be empty, as you cannot change the capacity of the array instance (it just sounds weird to say you can't change it's length, I dunno why). Every time you do this, you create another instance of an array that can never be used. Doing this a lot may result in wasted GC and memory pressure, thus the warning.

与其创建空数组,不如建议使用Array.Empty< T>().此方法使用此静态类返回一个数组

Instead of creating empty arrays, just use Array.Empty<T>() as it suggests. This method returns an array using this static class

internal static class EmptyArray<T>
{
    public readonly static T[] Value;

    static EmptyArray()
    {
        EmptyArray<T>.Value = new T[0];
    }
}

由于它是静态且只读的,因此在整个appdomain中只有一个空数组实例.空数组本质上是不可变的,因此缓存实例不是问题.如果发现自己盯着创建大量空数组的优雅代码路径,它可以让您在算法中放弃特殊情况下的空数组创建.

Since it's static and readonly, there's only ever one instance of this empty array in the entire appdomain. An empty array is essentially immutable, so caching the instance isn't a problem. And it allows you to forego special-casing empty array creation in your algorithms, if you find yourself eyeballing an elegant codepath that is creating tons of empty arrays.

Enumerable.Empty< T>()是Linq to Objects的等效项,对于不浪费空内容的分配也很有用.

Enumerable.Empty<T>() is the Linq to Objects equivalent and is also useful for not wasting allocations for empty stuff.

这篇关于新的object [] {}与Array.Empty&lt; object&gt;()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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