tags:

views:

67

answers:

5

Is there any relation to memory optimization when we call a method by using an interface. Is only that method loaded in memory? When a invoke a method via an object are all the methods of that object loaded into memory?

+5  A: 

Interface based programming does not relate to memory consumption - it is a technique to increase separation of concerns.

When you use an interface as a parameter (for example), you will still need to pass in an actual object that implements that interface. You will be accessing it via the interface and you could replace it with any other object that implements the interface. This is how you create a decoupled method. You still need memory for the actual object passed in.

Oded
suppose i have a property class P, a class C containing no data member only method definitions. when i crate object of C no memory allocated to it.when i call the method by the object of C all method get loaded into the memory. but when i call through interface on the calling function is loaded in the memory...
vksh
not much sure but just an assumption
vksh
@vikesh - Interfaces cannot be instantiated. Only objects can be. Of course if one implementation requires less memory, then if you use it, less memory will be used.
Oded
+2  A: 

It doesn't matter if you call a method via an interface or via a reference to the object. An interface reference still references an instance. The type has a number of methods and these are loaded as the type is loaded (and JIT compiled as needed).

Brian Rasmussen
A: 

No, there is no practical difference between calling a method using an interface and calling it using a class.

When you use an interface, it's just your reference that is different. The reference still points to an instance of a class. There can't be an instance of an interface as the interface itself doesn't contain any implementation, so there is always an instance of a class in the other end.

Guffa
A: 

What methods are loaded into memory has nothing to do with interfaces. In .NET, when a method is first called, it is compiled into native code, which is then kept in the memory. It doesn't matter how are you accessing it (whether directly, through interface, or using a delegate).

Also, memory consumption by methods themselves should be really low and nothing you should care about.

svick
A: 

Slightly vague question. I'm guessing you are asking if using interfaces incur performance penalties in whatever language you're using.

The answer is generally.. for C++ (pure virtual functions), yes. Can be significant in certain very-many-calls situations.

For Java (and .Net probably), not really.

See: http://stackoverflow.com/questions/890687/overhead-of-implementing-an-interface

Magnus Wolffelt