简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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