Edit 3: The problem is not parsing.
This is with how you read the file . If you read it correctly, it will be faster; however, your reading seems unusually slow. My initial suspicion was that it was due to redundant allocations, but it looks like there might be other problems with your code, as this does not explain the whole slowdown.
However, here the code snippet that I made completely avoids all object distributions:
static void Main(string[] args) { long counter = 0; var sw = Stopwatch.StartNew(); var sb = new StringBuilder(); var text = File.ReadAllText("spacestation.obj"); for (int i = 0; i < text.Length; i++) { int start = i; while (i < text.Length && (char.IsDigit(text[i]) || text[i] == '-' || text[i] == '.')) { i++; } if (i > start) { sb.Append(text, start, i - start);
with this parser:
const int MIN_POW_10 = -16, int MAX_POW_10 = 16, NUM_POWS_10 = MAX_POW_10 - MIN_POW_10 + 1; static readonly float[] pow10 = GenerateLookupTable(); static float[] GenerateLookupTable() { var result = new float[(-MIN_POW_10 + MAX_POW_10) * 10]; for (int i = 0; i < result.Length; i++) result[i] = (float)((i / NUM_POWS_10) * Math.Pow(10, i % NUM_POWS_10 + MIN_POW_10)); return result; } static float Parse(StringBuilder str) { float result = 0; bool negate = false; int len = str.Length; int decimalIndex = str.Length; for (int i = len - 1; i >= 0; i--) if (str[i] == '.') { decimalIndex = i; break; } int offset = -MIN_POW_10 + decimalIndex; for (int i = 0; i < decimalIndex; i++) if (i != decimalIndex && str[i] != '-') result += pow10[(str[i] - '0') * NUM_POWS_10 + offset - i - 1]; else if (str[i] == '-') negate = true; for (int i = decimalIndex + 1; i < len; i++) if (i != decimalIndex) result += pow10[(str[i] - '0') * NUM_POWS_10 + offset - i]; if (negate) result = -result; return result; }
this happens in a fraction of a second .
Of course, this analyzer is poorly tested and has these current limitations (and more):
Do not try to parse more digits (decimal and integer) than provided in the array.
No error handling.
Checks only decimal places , not exponents! that is, he can analyze 1234.56 , but not 1.23456E3 .
Does not care about globalization / localization. Your file is in only one format, so it makes no sense to take care of this because you are probably using English to store it.
It doesn't seem like you need a lot of kink, but look at your code and try to figure out the bottleneck. This does not seem to be reading or parsing.
source share