Samsung / TizenFX

C# Device APIs for Tizen

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Performance] Adhere to microsoft best practices for structs.

Mrnikbobjeff opened this issue · comments

I took a look at struct usage in TizenFX as this is a pet peevee of mine. I started looking in EflSharp and found out the following:

  • Marshal.PtrToStructure boxes unnecessariy, we should use Marshal.PtrToStructure to avoid the senseless box

  • Tons of structs should be readonly. I see implicit operators for creating structs from an IntPtr as being the only construction. These structs will be needlessly defensively copied.

  • This one is actually more optional which suprises me greatly, but I checked all calls to structs made in EflSharp and we never call Equals on them or store any struct in a container using IEquatable as an insertion strategy. Some structs implement IComparable and are used like IEquatable (CompareTo(x) == 0) and definitely should implement both. If we audit the structs anyway we might as well do this. The exact guidelines are in the docs, but I will copy paste something I wrote for Xamarin.Essentials in a ticket to give a brief overview:

I just wanted to clarify the post I made which I guess somehow promted this ticket. Structs can be compared fast via memcmp if they have no pointers in them (aka most of our structs). It also has to be properly packed, as defined in the StructLayout docs.
We need to override the equals implementation for structs which contain primitive types with value equality but not memory equality even if they are properly packed. E.G. double or float. Otherwise a reflection based approach is used which is an order of magnitude slower. Should such a malformed struct ever be used in a HashSet a variety of other perf problems arise, as certain structs can be created to have abhorrent performance when used this way. Simply create a struct where the first field returns the same hashcode (e.g. an int field being 0 99% of the time) and you have a nice Hash flooding attack

Thanks for information to improve performance
but EflSharp is outdated, we not use it