I use Unity. but this engine cannot use Span .. so, I made string parsing function
My function purpose is converting string to Single struct value(int, float, bool, UnityEngine.Vector4 etc..) and i thought about how to not generate GC as much as possible
string data is read xml file Examples of string data specifications are: "-1234.23,234,-.232.344", "554", "-.55"
During the test, I found something interesting
public unsafe Vector4 GetVectorToStackAlloc()
{
Vector4 vec = Vector4.Zero;
char* data = stackalloc char[8];
int dot = -1;
int index = 0;
int colume = 0;
for (int i = 0; i < Str.Length; ++i)
{
if (Str[i] == Token)
{
Parse();
dot = -1;
index = 0;
colume++;
}
else
{
if (Str[i] == '.') dot = index;
data[index++] = Str[i];
}
}
Parse();
void Parse()
{
if (index == 0) return;
bool isMinus = data[0] == '-';
int length = isMinus ? 1 : 0;
int mul = dot != -1 ? (dot - index) + 1 : 0;
for (int x = index - 1; x >= length; --x)
{
if (data[x] == '.') continue;
int k = data[x] - '0';
float m = MathF.Pow(10, mul++);
vec[colume] += k * m;
}
if (isMinus) vec[colume] *= -1;
}
return vec;
}
public Vector4 GetDefaultVector()
{
Vector4 vec = Vector4.Zero;
string[] split = Str.Split(Token);
for (int i = 0; i < split.Length; ++i)
{
if (string.IsNullOrWhiteSpace(split[i])) continue;
vec[i] = float.Parse(split[i]);
}
return vec;
}
public Vector4 GetSpanVector()
{
Vector4 vec = Vector4.Zero;
Span<char> span = stackalloc char[8];
int index = 0;
int colume = 0;
for (int i = 0; i < Str.Length; ++i)
{
if (Str[i] == ',')
{
if (index == 0) { vec[colume++] = 0; }
else vec[colume++] = float.Parse(span);
index = 0;
span.Clear();
}
else span[index++] = Str[i];
}
vec[colume] = float.Parse(span);
return vec;
}
During the testing process, I discovered that there was overhead in float.Parse() function and tested with a single float
public unsafe float GetStackAllocFloat()
{
float value = 0;
char* data = stackalloc char[8];
int dot = -1;
int index = 0;
for (int i = 0; i < Str.Length; ++i)
{
if (Str[i] == '.') dot = index;
data[index++] = Str[i];
}
if (index == 0) return value;
bool isMinus = data[0] == '-';
int length = isMinus ? 1 : 0;
int mul = dot != -1 ? (dot - index) + 1 : 0;
for (int x = index - 1; x >= length; --x)
{
if (data[x] == '.') continue;
int k = data[x] - '0';
float m = MathF.Pow(10, mul++);
value += k * m;
}
if (isMinus) value *= -1;
return value;
}
public unsafe float GetDefaultFloat()
{
return float.Parse(Str);
}
I think it is better to use stackalloc if the test method is normal.
Had I made mistake?
