views:

66

answers:

3

How are those different Method types handled in memory.

I found two different explanations to this:

  1. Static methods are only once in memory, whereas instance methods are in memory multiple times, one for each instance to handle the references to membervariables correctly in each instance.

  2. All methods are only once in memory and instance methods do only get the instance of the object as parameter.

What way is used by the different compilers?

A: 

Both are in memory only once. The only difference is that instance methods get another first argument: The instance of the class itself.

What does exist multiple times in memory (at least for .NET) are generic classes and their respective specific uses. If you use both a List<int> and a List<string> then you'll end up with two JITted copies of the code, one specific to int, one for string.

Joey
+1  A: 

The short answer, as Johannes said, is nearly always #2. Both will only exist in memory in a single location, but instance methods have context (which is basically an extra hidden argument) that gives them access to the instance.

But: Some languages/environments will instantiate a function that looks (to a naive reading of the source code) like one function multiple times. JavaScript is a good example of this: The function object closes over the scope in which it's defined, so if there are multiple scopes (such as a function being called more than once), multiple distinct function objects result. (Interpreters/JIT-ers may optimize whether the code is duplicated, but conceptually it is and the function references differ.)

Here's an example in JavaScript:

function foo() {

    alert("hi there");
}

function buildBar(x) {

    function bar() {
        alert(x);
    }

    return bar;
}

var f1, f2;

f1 = foo;
f2 = foo;
f1();
// alerts "hi there"
f2();
// alerts "hi there"
alert("f1 === f2 ? " + (f1 === f2));
// alerts "true", there is only one `foo`

var b1, b2;

b1 = buildBar("one");
b2 = buildBar("two");
b1();
// alerts "one"
b2();
// alerts "two"
alert("b1 === b2 ? " + (b1 === b2));
// alerts "false", there are two `bar`s

This becomes relevant in certain implementations of "private" instance data in JavaScript, where people define the instance methods within the constructor (much as buildBar defines bar) so they have access to private variables declared within the constructor. This has the desired effect (private instance data), but the impact of multiple function instances -- one for each instance of the object.

T.J. Crowder
A: 

Instance methods can be virtual. So for each runtime instance of an object with virtual methods, the run-time environment keeps an administration of references to the virtual methods. But the methods only have to exist once in memory (but it's the runtime environment which decides how many times it loads a method in memory).

For non-virtual methods the references can be determined at compiler time.

Hans van Dodewaard