0

Let's say that I need to access variable 'asdf' about 1000 times.

What will be faster : create object Foo and pass it as argument to bar constructor and access it via getter or access Foo's number statically. Or those 2 approaches have equal performance ?

Class Foo {
   public int asdf;
} 

Class Bar {
   Foo foo;
   Bar(Foo foo1) {
      this.foo = foo;
   }
   public void funcBar() {
        foo.asdf;
   }
}

Class Foo {
   public static int asdf;
} 

Class Bar {
   public void funcBar() {
        Foo.asdf;
   }
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248
red_asparagus
  • 349
  • 4
  • 16
  • 4
    Passing a reference has a negligible performance overhead, and is cleaner. – cs95 Aug 03 '17 at 20:20
  • 1
    please note that 1000 times is so infinitesimal that you should use the cleanest way, not the fastest - unless you are doing reeeaaally high performance stuff (which you probably should not do with java) – luk2302 Aug 03 '17 at 20:21
  • Generally, you should only worry about performance enhancement when you've got a performance issue – ControlAltDel Aug 03 '17 at 20:30
  • Any feedbacks on the answers you got? – GhostCat Aug 04 '17 at 09:18

2 Answers2

7

1000 times is nothing.

Thus you write that code that gets the job done using a straight forward and "clean" way.

Worry about good design instead of wasting your time solving non existent performance problems.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
2

As a pure answer to your question, according to SO user Mike Nakis, static calls are going to be fastest, followed by non-virtual, and then virtual. You can see his answer here. Still, go for code readability. It is better to have clear, maintainable code than one that squeezes every single ounce of performance out, but cannot be understood by other developers. In many cases, the speed of the retrieval is negligible.

Nick Clark
  • 1,414
  • 2
  • 16
  • 24