1

GWT 生成的 javascript 代码HashMap.iterator()非常HashSet.iterator()慢。有没有办法加快速度?

4

1 回答 1

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 #语言

于 2012-09-05T13:34:30.250 回答