Vector3.Equals without memory allocation?

In my A* pathfinding project I use a hashset for my closed-list (a list of nodes that have been checked already).
When running the profiler I noticed something funny, running 20 instances created 3KB GC allocation (per frame) from the Hashset.Contains() function. After googleing I found out that Vector3.Equals() uses a copy of the vector3 and thus create garbage.
I tried using a Hashset(float) instead, didn’t work. Found out that arrays dont create a hashcode that reflects the elements inside of it.

Anyone have an idea how I can create a hashset (I would like to have Contains() with O(1)) for a vector3 without memory allocation?
I also read that there is a GetHashCode-function for vector3, but the default comparer is Equals(). How do I change this (the default comparer) for the hashset? Will it solve my problem?

I haven’t checked, but I am guessing Vector3.Equals is being passed an object, or casts to an object internally for some reason. If so, then it would allocate memory, as the input parameter has to be ‘boxed’ to be passed as an object.

The hash set generic can take a generic equality comparer. Inside your comparer you can write any comparison you like - such as directly comparing the 3 floating point components, thus avoiding the problem:

That said, if you’re doing an A* search algorithm, might be better off working on an integer grid anyway? Then you can encode an x/y(/z?) position into a single ulong, which makes it super quick to look up and, far less memory intensive.

-Chris