normal casting vs Nonalloc casting

Hello could someone please tell me the difference between nonalloc casting like BoxCastNonAlloc() and normal BoxCastAll()

what are the advantages and disadvantages of each and scenarios under which we would like to use either one of them?

Both serve the same purpose in general, but they have some advantages / disadvantages:

Physics.BoxCastAll

Pro:

  • Easy to use.
  • Returns an array with the required size in order to return all hits

Con:

  • Allocates a new array each time it’s called which produces a lot garbage which can have a performance impact since the garbage collector has to clean up all the allocated memory

Physics.BoxCastNonAlloc

Pro:

  • Can re-use a pre-allocated array of RaycastHit structures and therefore doesn’t allocate any memory when called.
  • It does not return a new array but instead how many elements have been written into the pre allocated array.

Con:

  • Since the array need to be pre allocated it has a fix size of elements that can’t change.
  • The usage is slightly more complicated since you have to use the returned int count when iterating through the results.
  • If the cast would have hit more objects than you have allocated elements in your array, those results can not be returned and are lost.

Generally the Non Alloc versions are in most situations the better choices. However you have to think about how large you want to allocate the array to ensure you don’t miss anything important. If you cast against a certain group of objects on a certain layer and you know there are only 8 object at max, using an array with 10 elements should cover all cases with some reserve. If the count varies heavily you want to create an array with enough elements (like 30,100, 400 or even 1000).

When to use what highly depends on your target platform, if you can live with the generated garbage, if you can afford a large pre allocated array and on your general usecase (how many possible hits, how often it is used, …)