Hi Guys,
I am trying to make string from FColor array in Hex format(RRGGBB) from Texture. It works with TArray, but take a lot of resource (game freeze at 1-2 sec).
Maybe you know better way how to do it?
As for now, I use Parallel For function to make FString array (also possible, but it will require code changes further). It works faster,but not ideal. Maybe somebody know better option?
Your code is doing so much work behind the scenes, the most laborious of which is reallocating the whole destination string over and over again when you add an element. Additionally calling ToHex() allocates a string, and internally it uses Printf which allocates a string, and then Left(6) allocates a string…
I believe the most optimized way to do this is (this is just example code and hasn’t been tested or compiled, there might be some errors but it should get you started):
//allocate all the space we need in advance
//I wonder if there's some more convenient constructor for FString that can handle this
FString dest;
TArray<TCHAR>& chars = dest.GetCharArray();
chars.AddUninitialized(numColors * 6 + 1);
chars[chars.Num() - 1] = 0; //don't forget the null terminator
//this array will help us convert the values to hex
const TArray<TCHAR>& hexChars = TEXT("0123456789ABCDEF").GetCharArray();
const int32 nColors = colors.Num();
for (int32 i = 0; i < nColors; i++)
{
//find the proper index in the destination string to write to
const int32 cIndex = i * 6;
//use bit operations to find the right two characters from hexChars for each color component
const FColor& col = colors[i];
chars[cIndex] = hexChars[(col.R & 0xF0) >> 4];
chars[cIndex + 1] = hexChars[ col.R & 0xF];
chars[cIndex + 2] = hexChars[(col.G & 0xF0) >> 4];
chars[cIndex + 3] = hexChars[ col.G & 0xF];
chars[cIndex + 4] = hexChars[(col.B & 0xF0) >> 4];
chars[cIndex + 5] = hexChars[ col.B & 0xF];
}
@RotemS Great idea, thanks a lot! I will move in this way and come back with results at couple of days