GWT为HashMap.iterator()
和HashSet.iterator()
生成的javascript代码非常慢。有没有办法加快速度?
答案 0 :(得分:3)
非常慢?你必须更具体一点。这是一个总结100000个数字的小例子:
final int N = 100000;
final long startInsert = System.currentTimeMillis();
final HashSet<Integer> set = new HashSet<Integer>(N);
for (int i = 0; i < N; i ++)
set.add(i);
final long stopInsert = System.currentTimeMillis();
RootPanel.get().add(new Label(
"Time to insert: " + (stopInsert - startInsert) + "ms"));
final long startIterate = System.currentTimeMillis();
final Iterator<Integer> iterator = set.iterator();
int sum = 0;
while (iterator.hasNext()) {
final Integer integer = iterator.next();
sum += integer;
}
final long stopIterate = System.currentTimeMillis();
RootPanel.get().add(new Label("Sum: " + sum +
", Time to iterate: " + (stopIterate - startIterate) + "ms"));
让我们在Core2 Duo上试试这个:
这是Firefox 15(编译模式)中的输出:
Time to insert: 490ms
Sum: 4999950000, Time to iterate: 766ms
Chrome 21(编译模式):
Time to insert: 130ms
Sum: 4999950000, Time to iterate: 105ms
这比开发模式慢:
Firefox 15(开发模式):
Time to insert: 16ms
Sum: 704982704, Time to iterate: 12ms
Chrome 21(开发模式):
Time to insert: 59ms
Sum: 704982704, Time to iterate: 10ms
但是考虑到这是JavaScript与Java,结果实际上非常好。
(顺便说一句,如果有人想知道为什么Java(704982704)的总和与JavaScript(4999950000)相比有所不同......这是预期的,请参阅https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsCompatibility#language)