23 ms·
Most of what I'm doing isn't writing non-idiomatic code, but following different idioms. Avoid instantiating classes (including Dictionaries and Lists) with new
by Kapura 9y ago
Most of what I'm doing isn't writing non-idiomatic code, but following different idioms. Avoid instantiating classes (including Dictionaries and Lists) with new every frame, cache data you know you'll need to use again, avoid boxing/unboxing (casting to and from the 'object' type).
I can't share any of my own code, but the sort of things that I'm doing can be exemplified by these two functions from Unity's physics API: [1][2].
The first returns a newly allocated array of the data, while the second takes, as a parameter, the array to populate and returns only the number of elements that it populated. If I know I'm going to be doing a big raycast each frame, I can instantiate the output array to a reasonable size in my class declaration not have to pay the price of the garbage created by allocating a new array every frame.
[1] https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html https://docs.unity3d.com/ScriptReference/Physics.RaycastAll....
[2] https://docs.unity3d.com/ScriptReference/Physics.RaycastNonAlloc.html https://docs.unity3d.com/ScriptReference/Physics.RaycastNonA...