Java Specialists' Java Training Europehome of the java specialists' newsletter

The Java Specialists' Newsletter
Issue 0702003-05-17 Category: Performance Java version:

Subscribe Free RSS Feed

Muitas dimenões são ruins para você

by Dr. Heinz M. Kabutz
Special Thank You! I would like to thank Rafael Steil from the Grupo de Usuarios Java - GUJ, from Brazil for translating our newsletters into Portuguese. In addition, I would like to thank Vanessa Sabino for assisting Rafael in the translation work. Disclaimer: Since I do not know any Portuguese, I make no warranty for the accuracy of the translation. Heinz

Bem vindo à edição de número 70 da The Java(tm) Specialists' Newsletter, onde daremos uma breve olhada em arrays multi-dimensionais. Vários artigos estão disponíveis sobre este problema, então, nesta newsletter, irei direto ao ponto com um exemplo. Gostaria de agradecer a Roy Emmerich (Peralex in Cape Town), Pieter Potgieter e Louis Pool from Grintek Ewation por me lembrarem deste problema e por enviarem um programa de teste que ilustra isso.

Would you like to really understand Java concurrency? Join us for an in-depth study of how threading works in Java. During the course, you will learn how to write correct and fast multi-threaded Java code. Please click here if you would like to learn more.

Muitas dimensões são ruins para você

Uma das coisas que aprendemos na escola primária do Java é que devemos evitar arrays multi-dimensionais assim como evitamos uma praga. Um array é um objeto por natureza, e quando você tem arrays de várias dimensões, você tem arrays de objetos. Navegar por eles consome um processamento considerável. Ao invés de construir um array multi-dimensional de tamanho n por m, construa um array de uma única dimensão de tamanho n vezes m e então calcule a posição você mesmo.

public class MultiDimensions {
  private final static int NUM_BINS = 1000;
  private final static int ITERATIONS = 10000;

  public static void main(String[] args) {
    testMultiArray();
    testMultiArray2();
    testSingleArray();
  }

  private static void testMultiArray() {
    long time = -System.currentTimeMillis();
    // Apenas certificando que o número de operações é igual
    int ops = 0;

    for (int repeat = 0; repeat < ITERATIONS; repeat++) {
      int[][] aTwoDim = new int[NUM_BINS][4];
      for (int i = 0; i < aTwoDim.length; i++) {
        for (int j = 0; j < aTwoDim[i].length; j++) {
          ops++;
          aTwoDim[i][j] = j;
        }
      }
    }

    time += System.currentTimeMillis();
    System.out.println(ops);
    System.out.println("Tempo necessário para [][4] - " + time);
  }

  private static void testMultiArray2() {
    long time = -System.currentTimeMillis();
    int ops = 0;

    for (int repeat = 0; repeat < ITERATIONS; repeat++) {
      int[][] aTwoDim = new int[4][NUM_BINS];
      for (int i = 0; i < aTwoDim.length; i++) {
        for (int j = 0; j < aTwoDim[i].length; j++) {
          ops++;
          aTwoDim[i][j] = j;
        }
      }
    }

    time += System.currentTimeMillis();
    System.out.println(ops);
    System.out.println("Tempo necessário para [4][] - " + time);
  }

  private static void testSingleArray() {
    long time = -System.currentTimeMillis();
    int ops = 0;

    for (int repeat = 0; repeat < ITERATIONS; repeat++) {
      int[] aOneDim = new int[NUM_BINS * 4];
      for (int i = 0; i < aOneDim.length/4; i++) {
        for (int j = 0; j < 4; j++) {
          ops++;
          aOneDim[i*4 + j] = j;
        }
      }
    }

    time += System.currentTimeMillis();
    System.out.println(ops);
    System.out.println("Tempo necessário  para [] - " + time);
  }
}

Em meus testes usando um cliente hotspot JDK 1.4.1, tive o seguinte resultado:

40000000
Tempo necessário para [][4] - 4226
40000000
Tempo necessário para [4][] - 631
40000000
Tempo necessário para [] - 671

Com um hotspot server, os resultados são ligeiramente melhores:

40000000
Tempo necessário para [][4] - 3675
40000000
Tempo necessário para [4][] - 350
40000000
Tempo necessário para [] - 561

Os resultados são esclarecedores. Se voce tem um array com um index primário grande, você se dará melhor usando um array de dimensão única. Sob o server hotspot, o array multi-dimensional com um index primário pequeno se sai um pouco melhor que o array de dimensão única.

Isso é tudo que eu gostaria de dizer para esta newsletter. Você foi avisado que ela seria curta :-)

Atenciosamente,

Heinz

Performance Articles Related Java Course Discuss at The Java Specialist Club

    
Your Name

Your E-Mail

Your Phone

Your Company

Your Comment


Java Master
Java Concurrency
Design Patterns
In-House Courses



© 2010 Heinz Kabutz - All Rights Reserved Sitemap seo web design Catch22 Marketing
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. JavaSpecialists.eu is not connected to Oracle, Inc. and is not sponsored by Oracle, Inc.