- Home /
Conversion of float[] to byte[] is too slow, how to optimize this?
I am making a voxel game, and to save the voxel data, that is a float[,,] variable, I divide then in nine float[] variables( to avoid out of memory issue ), and call the function to convert this float[] to byte[]
here is these function:
static function float1dprabyte (floataux : float[],zeros : int) {
var tempo : int =System.Environment.TickCount;
var intuando : int[]=new int[floataux.Length];
var byteArray : byte[] = new byte[floataux.Length*4];
for(var j=0;j<intuando.Length;j++)
{
intuando[j]= Mathf.FloorToInt(floataux[j]*(Mathf.Pow(10,zeros)));
var bytinho : byte[] = new byte[4];
bytinho =System.BitConverter.GetBytes(intuando[j]);
byteArray[(j*4)] = bytinho[0];
byteArray[(j*4)+1] = bytinho[1];
byteArray[(j*4)+2] = bytinho[2];
byteArray[(j*4)+3] = bytinho[3];
}
tempo -= System.Environment.TickCount;
Debug.Log("float1dprabyte : "+tempo);
return(byteArray);
}
and to load then i use a reverse function:
static function byteprafloat (meuint32: byte[],zeros : int) {
var tempo : int = System.Environment.TickCount;
var intuando : int[]=new int[meuint32.Length/4];
var Mx : int = 300;
var My : int = 120;
var Mz : int = 300;
var floataux : float[] = new float[Mx*My*Mz];
for(var j=0;j<meuint32.Length-4;j+=4)
{
intuando[j/4] =System.BitConverter.ToInt32(meuint32,j);
floataux[j/4] = (1.0*intuando[j/4])/(Mathf.Pow(10,zeros));
}
tempo -= System.Environment.TickCount;
Debug.Log(" byteprafloat : "+tempo);
return(floataux);
}
and this is too slow, 1000 milisseconds for convert a float[300*120*300] into a byte[300*120*300*4] and 3000 miliseconds to convert a byte[300*120*300*4] into a float[300*120*300], with 9 slices of these, to make the complete float[900,120,900] voxel data, the save/load is to much slow...
how I can optimize this?
Why are you converting from float to byte in the first place? 4 bytes takes just as much memory as one float, so it seems like a lot of needless conversion.
Also, I think you can entirely skip the Pow and FloorToInt. If you want to turn floats to bytes, just use BitConverter.GetBytes and then BitConverter.ToSingle.
I need to save the data, using WriteAllBytes... and I dont know how to save floats direct....
but a float, is made by 32bits == 4 bytes; so,4 bytes ocuppies the same memory that a float
thanks! now elapses 300 miliseconds to load and 1100 to save