我工作的任务分配时,输入的是在下面的格式,我必须以最快的速度解析它地:速度优化的树数据解析器
5 (
5 (
3 (
)
)
3 (
3 (
)
3 (
)
)
5 (
2 (
)
4 (
)
)
)
它是“树结构员工“,这些数字用于后续任务(语言索引)。
每个员工可以有任何数量的下属和一个上级(根节点是“老板”)。
这里是我的解析器:(本来我用Scanner
,这是短期和简单,但约两倍慢)
// Invocation
// Employee boss = collectEmployee(null, 0, reader);
private Employee collectEmployee(final Employee parent, int indent, final Reader r) throws IOException
{
final StringBuilder sb = new StringBuilder();
boolean nums = false;
while (true) {
char c = (char) r.read();
if (c == 10 || c == 13) continue; // newline
if (c == ' ') {
if (nums) break;
} else {
nums = true;
sb.append(c);
}
}
final int lang = Integer.parseInt(sb.toString());
final Employee self = new Employee(lang, parent);
r.skip(1); // opening paren
int spaces = 0;
while (true) {
r.mark(1);
int i = r.read();
char c = (char) i;
if (c == 10 || c == 13) continue; // newline
if (c == ' ') {
spaces++;
} else {
if (spaces == indent) {
break; // End of this employee
} else {
spaces = 0; // new line.
r.reset();
self.add(collectEmployee(self, indent + 1, r));
}
}
}
return self; // the root employee for this subtree
}
我需要刮胡子几个循环时的代码,所以它会通过严格的要求。我已经介绍过它,这部分确实是减慢了应用程序的速度。输入文件最多可以有30个MiB,所以任何小小的改进都会产生很大的差异。
任何想法赞赏。谢谢。
(只是为了保持完整性,扫描仪实现是在这里 - 它可以给你的想法,我是如何解析它)
private Employee collectEmployee(final Employee parent, final Scanner sc)
{
final int lang = Integer.parseInt(sc.next());
sc.nextLine(); // trash the opening parenthesis
final Employee self = new Employee(lang, parent);
while (sc.hasNextInt()) {
Employee sub = collectEmployee(self, sc);
self.add(sub);
}
sc.nextLine(); // trash the closing parenthesis
return self;
}
我试过正是(1),它是慢了很多:( 我真的不知道为什么,但StringBuilder的和parseInt函数是在这种情况下更快。 – MightyPork 2015-03-02 14:46:00
听起来很可疑,因为在整.parseInt做了一些技巧来加速解析连续的数字,你所拥有的数字太小以至于不能解决这个问题。唉,因为我没有你的替代代码,我不能希望解开这个难题。 – llogiq 2015-03-02 14:55:10
After大量的摆弄和结合的方法,我得到它的工作,谢谢 – MightyPork 2015-03-02 15:25:58