-Performance

This commit is contained in:
James Newton-King
2013-03-30 16:59:08 +13:00
parent 2bf88ebba0
commit 73187dde1e
3 changed files with 74 additions and 3 deletions
@@ -1110,6 +1110,44 @@ bye", reader.Value);
}
}
[Test]
public void ParseIntegers()
{
JsonTextReader reader = null;
reader = new JsonTextReader(new StringReader("1"));
Assert.AreEqual(1, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader("-1"));
Assert.AreEqual(-1, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader("0"));
Assert.AreEqual(0, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader("-0"));
Assert.AreEqual(0, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader(int.MaxValue.ToString()));
Assert.AreEqual(int.MaxValue, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader(int.MinValue.ToString()));
Assert.AreEqual(int.MinValue, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader(long.MaxValue.ToString()));
reader = new JsonTextReader(new StringReader("1E-06"));
ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader("1.1"));
ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader(""));
Assert.AreEqual(null, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader("-"));
ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32());
}
[Test]
public void WriteReadWrite()
{
+1 -3
View File
@@ -1185,9 +1185,7 @@ namespace Newtonsoft.Json
}
else
{
string number = _stringReference.ToString();
numberValue = Convert.ToInt32(number, CultureInfo.InvariantCulture);
numberValue = ConvertUtils.IntParseFast(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
}
numberType = JsonToken.Integer;
@@ -563,5 +563,40 @@ namespace Newtonsoft.Json.Utilities
return false;
}
}
public static int IntParseFast(char[] value, int start, int length)
{
if (length == 0)
throw new FormatException("Input string was not in a correct format.");
bool isNegative = (value[start] == '-');
if (isNegative)
{
// just a negative sign
if (length == 1)
throw new FormatException("Input string was not in a correct format.");
start++;
length--;
}
int result = 0;
int end = start + length;
for (int i = start; i < end; i++)
{
char c = value[i];
if (!(c >= '0' && c <= '9'))
throw new FormatException("Input string was not in a correct format.");
result = 10 * result + (c - 48);
}
if (isNegative)
result = 0 - result;
return result;
}
}
}