Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I had a C# project that was too slow and used too much RAM.

I can attest that structs use less memory however IIRC they don't have methods so no GetHashCode() which made them way too slow to insert in a HashSet or Dictionary.

In the end I used regular objects in a Dictionary. RAM usage was a bit higher than structs (not unbearably so) but speed improvement was massive.



1. structs can have methods 2. the primary value of value types is not to use less ram (you just save a pointer, I guess times two because of GC) but the ability to avoid having to GC the things, since they are either on the stack or in contiguos chunks of memory, and to leverage cpu caches are you can iterate over contiguous data rather than hopping around in the heap. Iterating over contiguous data can be a large constant factor faster than over a collection of pointers to heap objects.


>I can attest that structs use less memory however IIRC they don't have methods so no GetHashCode() which made them way too slow to insert in a HashSet or Dictionary

You can and should implement IEquatable on a struct, especially if you plan on placing them in a hashset - the default implementation will use reflection and will be slow but it's easy to override.


I just checked, apparently structs can have methods. Is it a new thing or me that was ignorant?


You could always have methods (for as long as I can remember at least, I started using .NET in 3.0 days), you just can't inherit structs or use virtual methods because structs don't have virtual method table. You can implement interfaces however and override operators - it's very nice for implementing 3D graphics math primitives like vectors and matrices, way better than Java in this regard which was what got me into C# way back then.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: