Java Empty and full class performance of methods



  • If I create a class that aims to group a number of related methods. Suppose a Class Boi{} and it has several methods but no element.

    For example:

    public class Ruminante{
          public String mugir(Animal animal){
                return "Muuu";
          }
          public void comer(Mato grama){
                 //processa grama
          }
          public void darCabecada(Animal animal){
    
      }
      public void darCoice(Animal animal){
    
      }
    

    }

    And when I want to call it,

    public class Principal(){
    Boi boi = new Boi();
    Ruminante r = new Ruminante();
    r.mugir(boi);
    }

    What is performance loss? Are there other disadvantages in doing this way? Is it much worse than if everything in the Ruminante class was static?



  • Java instance methods are by virtual pattern. This means that (except in static or marked methods as final) whenever one of them is called, there is one lookup in the virtual table of the object to determine whether the object is actually of the Ruminante class (and not of one of two subclasses) and depending on the class of the object, the pointer is obtained for the function that should be called. If the function is marked as static or final, then the linking is done statistically, that is, the lookup in the virtual table is not necessary, and the code is "more efficient".

    Now, having said the above paragraph, for the big, vast majority of applications this "performance loss" will not make any difference. Unless the case you are running the function in a very large loop, without other calls, the performance loss will be insignificant. In the vast majority of cases, you'd better write a code that makes sense (that someone can end it and keep it easily) that think about early optimizations. Or according to Donald Knuth: http://en.wikiquote.org/wiki/Donald_Knuth (premature optimization is the root of all evils).




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2