简体   繁体   English

C#-静态集合与集合作为​​单例字段的性能

[英]C# - Performance of static collections vs collections as fields of singleton

I would like to ask if there are differences in performance between static references to collections of objects vs having a singleton class and having the collections as normal fields of the singleton class. 我想问一下,静态引用对象集合与具有单例类以及将集合作为单例类的普通字段之间在性能上是否存在差异。

Static fields are stored in a different part of the heap as far as I know so isn't locality of reference better when using singletons in this case? 据我所知,静态字段存储在堆的不同部分中,因此在这种情况下使用单例时引用的局部性不是更好吗?

The only thing that is slow about static storage is a read or write to a static field. 关于静态存储的唯一慢的事情是对静态字段的读取或写入。 After you have obtained either the collection instance or the singleton instance from a static field there is no performance difference. 从静态字段获取集合实例或单例实例之后,就没有性能差异了。 You have an object reference now and are not touching static storage anymore. 您现在有了对象引用,并且不再接触静态存储。

Note, that the memory of an object referenced from a static field is not stored in that field. 请注意,从静态字段引用的对象的内存未存储该字段中。 It is stored on the heap. 它存储在堆中。 Only the reference to it is static storage. 仅对其的引用是静态存储。

The performance difference between static and instance storage is also very small. 静态存储和实例存储之间的性能差异也很小。

Now, what is faster? 现在,什么更快? The singleton-instance variant is slower because you have to pass through two memory deference operations to get to the collection instead of one. 单例实例变体较慢,因为您必须通过两次内存引用操作才能到达集合,而不是一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM