I'm curious why MemoryOwner<T> is implemented as a class instead of a struct. #1091
Replies: 1 comment
-
I'm not an author/contributor of this library, so I don't know the answer for sure. It could just be something like avoiding premature optimization (although this is a "HighPerformance" library) or it could just be "wrong". With that being said, there are probably good reasons for it. The guidance (i.e. rules that are broken all the time) I have always seen for deciding a Use a
I usually see those 4. Here's an example I found that references essentially the same guidance: https://stackoverflow.com/questions/521298/when-should-i-use-a-struct-rather-than-a-class-in-c It seems like there should be a 5th, that is kind of implied by those 4, but worth pointing out, which is the semantics you want. For example, do you want it to be passed by value or reference? Now, I'm not familiar with your implementation and only somewhat familiar with the implementation in this library. Using But, even so, I don't think most of the other things in the guidance list apply to the concept of a "memory owner". A "memory owner" doesn't represent any kind of single or primitive value. And it doesn't seem like it is/could be immutable (conceptually, at least). And I would guess it is either going to get copied pretty frequently or boxed/unboxed pretty frequently. As for your benchmark results, I'm not sure you should be surprised that the And it depends on what your benchmark is doing/testing. Are you just instantiating a bunch of instances of your implementation and Two final things:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I believe the title is clear. But a bit of context.
While refactoring some code to optimise it's memory usage, and without knowing I was actually creating a similar implementation of MemoryOwner when a colleague told me my code resembled a lot to what MemoryOwner has his purpose, providing a pooled byte[] with a specific lenght.
While performing some benchmarks in order to see which way to go forward, I could see MemoryOwner taking more memory than my implementation, which made me have a look on why this was the case.
I could see MemoryOwner is implemented as a class, while I had the idea to implement it as a struct instead.
After changing my implementation to a class (BuilderWithPooledRequestClassSetup in the benchmark), I could indeed see similar behaviour.
I am now wondering why this is the case and I also what potential pitfalls I have to take into consideration should I proceed with my struct implementation instead?
Beta Was this translation helpful? Give feedback.
All reactions