Philip-Trettner / GlmSharp

Open-source semi-generated GLM-flavored math library for .NET/C#
MIT License
47 stars 18 forks source link

Type comparison enhancement #10

Open ChargeProduction opened 7 years ago

ChargeProduction commented 7 years ago

Hello Philip, I created a method to compare structs more efficiently and applied it to the GlmSharp components.

Using the following unsafe code on mat4 runs about 10x faster inline than mat4.Equals(other). As an extension (mat4.EqualsVal(other)) it is much slower, but still about 2x as fast(may be faster on a better computer).


// mat and other are parameters. int size = 16; // 16 4 bytes ( = 16 ints) per mat4 mat4 ppA = (mat4)&mat, ppB = (mat4)&other; while (size-- > 0) { if (((int)ppA)[size] == ((int)ppB)[size]) continue; return false; } return true;


Maybe this could be even more efficient if the parameter 'mat' gets removed and be replaced by '&this' inside the function. Would save 64 bytes of stack allocation.

My benchmark is a simple for loop with 1.000.000 iterations, in Release mode with optimization, on a 3.3GHz Quadcore i3. Equals = ~90ms EqualsVal = ~45ms

cphillips83 commented 7 years ago
  1. Don't you have to pin both of these pointers so that the GC doesn't move the data in the middle of your code executing?

  2. You would also want conditional compilation on this with an UNSAFE param, I would imagine that you would want to support both cases since some environments and security policies wouldn't allow it to execute.

ChargeProduction commented 7 years ago

@cphillips83 1: There shouldn't be any problem. If you're calling a method which provides both matrices as parameters, you actually work with stack memory, which won't be garbage collected. Of course, if you use a reference to a previously created "new mat4", then it has to be pinned.

2: Using this library as a dll wouldn't require your code to be unsafe too. But which security effects it would have I can't say yet. I can do some research on it if you want.