[Newbies] Two questions about Smalltalk language design
bert at freudenbergs.de
Sun Dec 30 15:40:49 UTC 2012
On 2012-12-27, at 01:32, Sebastian Nozzi <sebnozzi at gmail.com> wrote:
> Why do ST methods return "self" if nothing is explicitly returned?
One very simple reason has not been stated yet: In the Virtual Machine, returning self is simpler and more efficient than returning any other object.
Smalltalk byte codes implement a stack machine. That means arguments are passed by pushing them onto a stack, rather than putting them into registers. In addition to the arguments as listed in the method signature, a hidden argument is always passed, which is the receiver of the message. So even for unary methods (those without arguments) the receiver is pushed onto the stack, then the method is executed, and the receiver value on the stack is how the method knows "self". By returning "self" if no explicit return statement is given, the VM can just leave the "self" oop on the stack, which saves at least one memory store operation. So from an efficiency and simplicity standpoint, returning "self" is the most elegant thing to do.
- Bert -
More information about the Beginners