I have this mesh that I want to read as fast as possible from json.
[Serializable]
public class Mesh
{
public int[] Faces { get; set; }
public Vec3[] Vertices { get; set; }
}
[Serializable]
public class Vec3
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
}
I've read that creating a manual Serializer and Deserializer is much faster than using reflection. So I tried to create my own:
public static Mesh FromJson(JsonTextReader reader)
{
var mesh = new Mesh();
var currentProperty = string.Empty;
List<int> faces = new List<int>();
List<Vec3> Vertices = new List<Vec3>();
double X = 0, Y = 0, Z = 0;
while (reader.Read())
{
if (reader.Value != null)
{
if (reader.TokenType == JsonToken.PropertyName)
currentProperty = reader.Value.ToString();
else if (reader.TokenType == JsonToken.Integer && currentProperty == "Faces")
faces.Add(Int32.Parse(reader.Value.ToString()));
else if (reader.TokenType == JsonToken.Float && currentProperty == "X")
{
X = float.Parse(reader.Value.ToString());
}
else if (reader.TokenType == JsonToken.Float && currentProperty == "Y")
{
Y = float.Parse(reader.Value.ToString());
}
else if (reader.TokenType == JsonToken.Float && currentProperty == "Z")
{
Z = float.Parse(reader.Value.ToString());
}
}
else
{
//Console.WriteLine("Token: {0}", reader.TokenType);
if (reader.TokenType == JsonToken.EndObject && reader.Path.Contains("Vertices"))
Vertices.Add(new Vec3 { X = X, Y = Y, Z = Z });
}
}
mesh.Faces = faces.ToArray();
mesh.Vertices = Vertices.ToArray();
return mesh;
}
Even though I managed to get a good 30% improvement (was expecting a bit more TBH) while Writing, reading is giving me trouble. I feel it has to do with the nesting of Vec3 because if I run a similar logic but without Vec3 I am getting decent results ~30%. The only examples I could find were dealing with simple data structures without nesting such as this so I feel I am handling it a bit simplistic here.