意外的Java性能

前端之家收集整理的这篇文章主要介绍了意外的Java性能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我刚刚抛出了所有关于Java优化的知识.我有以下任务:

给定表示比赛场地和场地位置的2D数组,填充另一个数组,其中包含玩家可以进入该区域中每个其他位置的步数.玩家可以向上,向下,向左和向右移动.例如,第一个邻居将全部为1,对角线全部为2.

对于第一次尝试,我尝试了一种简单的4向Floodfill算法.它的速度非常慢.

其次,我决定摆脱递归并使用一个简单的队列.它工作得很好,速度很快(非常大约20倍).这是代码

  1. private void fillCounterArray(int[] counters,int position) {
  2. Queue

现在,“常识”告诉我,使用静态数组和int-pointer的队列操作会更快.所以我删除了Queue并使用标准的int []数组.代码是相同的,除了类似队列的操作.它现在看起来像这样(你可以看到,我用来生活在C方:) :):

  1. private void fillCounterArray(int[] counters,int position) {
  2. // Array and its pointer.
  3. int[] queue = new int[900]; // max size of field
  4. int head = 0;
  5. // Obtain the possible destinations from position,check the valid ones
  6. // and add it the stack.
  7. int[] destination = board.getPossibleDestinations(position);
  8. for (int i = 0; i < destination.length; i++) {
  9. if (board.getBoard()[destination[i]] == Board.CLEAR) {
  10. counters[destination[i]] = 1;
  11. queue[head++] = dest[i];
  12. }
  13. }
  14. // Now fill up the space.
  15. while (head > 0) {
  16. int pos = queue[--head];
  17. int steps = counters[pos];
  18. destination = board.getPossibleDestinations(pos);
  19. for (int i = 0; i < destination.length; i++) {
  20. int dest = destination[i];
  21. if (board.getBoard()[dest] == Board.CLEAR && (counters[dest] > steps + 1 || counters[dest] == 0)) {
  22. counters[dest] = steps + 1;
  23. queue[head++] = dest;
  24. }
  25. }
  26. }
  27. }

当我运行这个“优化代码”时,它明显慢于使用Queue,速度只有递归技术的两倍.当我将数组声明为实例变量时,几乎没有任何区别.这怎么可能?

最佳答案
你在优化的同时颠倒了我的想法;

  1. The queue is fifo,first in first out
  2. The array is lifo,last in first out,as you walk it downwards

这通常会给你不同的表现;-)

猜你在找的Java相关文章