make Long.parseLong more efficient

This commit is contained in:
Joel Dice 2008-08-29 11:37:53 -06:00
parent 9017b5996a
commit e0e827596e
2 changed files with 9 additions and 1 deletions

View File

@ -128,15 +128,19 @@ public final class Long extends Number implements Comparable<Long> {
int i = 0; int i = 0;
long number = 0; long number = 0;
boolean negative = s.startsWith("-"); boolean negative = s.startsWith("-");
int length = s.length();
if (negative) { if (negative) {
i = 1; i = 1;
-- length;
} }
long factor = pow(radix, length - 1);
for (; i < s.length(); ++i) { for (; i < s.length(); ++i) {
char c = s.charAt(i); char c = s.charAt(i);
int digit = Character.digit(c, radix); int digit = Character.digit(c, radix);
if (digit >= 0) { if (digit >= 0) {
number += digit * pow(radix, (s.length() - i - 1)); number += digit * factor;
factor /= radix;
} else { } else {
throw new NumberFormatException("invalid character " + c + " code " + throw new NumberFormatException("invalid character " + c + " code " +
(int) c); (int) c);

View File

@ -102,6 +102,10 @@ public class Misc {
expect(foo > 0); expect(foo > 0);
} }
expect(Long.parseLong("25214903884") == 25214903884L);
expect(Long.parseLong("-9223372036854775808") == -9223372036854775808L);
expect(String.valueOf(25214903884L).equals("25214903884")); expect(String.valueOf(25214903884L).equals("25214903884"));
expect(String.valueOf(-9223372036854775808L).equals expect(String.valueOf(-9223372036854775808L).equals