Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead of implementing an interface

One of my colleagues told me that implementing interfaces introduces overhead. Is this true?

I am not concerned about micro optimizations; I just want to know the deeper details this entails.

like image 449
Joan Venge Avatar asked May 20 '09 23:05

Joan Venge


People also ask

What is an implementation of an interface?

An implementation of an interface is a Java program that references the interface using the implements keyword. The program is required to provide method logic for all non-default methods. Optionally, the program can provide an implementation of a default method defined in the interface.

What happens when you implement an interface?

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface.

What was the advantage of implementing the interface?

Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.

Which is the correct way to implement the interface?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.


1 Answers

couldn't resist and tested it and it looks like almost no overhead.

Participants are:

Interface IFoo    defining a method
class Foo: IFoo   implements IFoo
class Bar         implements the same method as Foo, but no interface involved

so i defined

Foo realfoo = new Foo();
IFoo ifoo = new Foo();
Bar bar =  new Bar();

and called the method, which does 20 string concatenations, 10,000,000 times on each variable.

realfoo:   723 Milliseconds
ifoo:      732 Milliseconds
bar:       728 Milliseconds

If the method does nothing, the actual calls stand out a bit more.

  realfoo: 48 Milliseconds
  ifoo: 62 Milliseconds
  bar: 49 Milliseconds
like image 110
Botz3000 Avatar answered Sep 22 '22 18:09

Botz3000