I keep the TArray of USTRUCT pointers. The type of USTRUCT is such that it has an FName property.
At some points during runtime I would like to modify specific members of my array, choosing them by the FName properties. I found out that TArray has the FindByKey method. Is there a way to use it for speeding up the process of finding the array element with specific FName? Because currently the only 2 ways how I can find that element is either looping through the whole array and checking the FName of each element, or using the TMap instead of TArray.
If you are using a TArray then yes you will need to iterate through the structure to find the element. A TMap (as you said) is precisely the data structure if you want quick access to a specific element via a key.
If you don’t have enough elements to justify the map, the TArray does support a the FindByPredicate method, which takes a predicate and finds the entry matching it. You can see examples of finding with a predicate here.
Looking at the source code, all FindByKey does is iterates through the array and checks if an element equals your key. This can be useful if your type overloads the operator== for another type. In general however, the FindByPredicate method will allow you to select an element using an arbitrary specifier.
If your array is static (ie. elements are only edited in editor, and never change during runtime), you can easily access them only by index.
In your struct just add another property int32 Index, and make sure it is always exactly the same as index of element in array.
This way you don’t have to perform any searches, you can access elements on array directly by their index.
Of course you still need to know index of element you are interested in, so this solution might not be perfect.
Otherwise, if you need fast random access to elements TMap is what you need. But be wary that performance of searching for TMap might be drastically lowered if there are duplicated keys.
thanks, in my case I am interested in searching specifically by FNames. I will use TArray and see, if it would be slower than I want it to be. Will just keep in mind that there is a space for optimization here