How are those different Method types handled in memory.
I found two different explanations to this:
-
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.
-
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?
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:
This becomes relevant in certain implementations of “private” instance data in JavaScript, where people define the instance methods within the constructor (much as
buildBardefinesbar) 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.