4 ms·
Encapsulation is making the internal representation of abstract data types not visible to their clients. In other words, it's a discipline for writing programs.
by catnaroek 10y ago
Encapsulation is making the internal representation of abstract data types not visible to their clients. In other words, it's a discipline for writing programs. Some languages (e.g., ML) just happen to helpfully enforce that discipline for you. It has no runtime impact whatsoever.
- qwertyuiop924 10y agoNot true. While the various abstractions themselves may have no runtime impact, they encourage programming in ways that, while they may be good for maintainability, aren't as fast. For example, if you're using ML, you'll likely represent a list of objects (say, structures representing addresses) by establishing a type for the objects, and keeping a list of them. A C programmer might use a statically allocated array, or actually embed a pointer to the next object in the list into the struct. The C program might be less maintainable, but it would be faster because it's doing less pointer chasing. An asm programmer might optimize further. Now, this is a fairly trivial example, and not too hard for a compiler to optimize out, IIRC, but it's just an example. Other instances of this are far harder to optimize away. The further up you are from the hardware, the less aware you are of the perf tradeoffs, and the less you can do to fix it. So if you want the best perf, go for asm.
- catnaroek 10y ago> For example, if you're using ML, you'll likely represent a list of objects (say, structures representing addresses) by establishing a type for the objects, and keeping a list of them. In ML, most of the time I don't work with objects at all. I work with values. The beauty of programming with values is that the language implementor can represent them however he wishes, as long as he respects the semantics of the operations on said values. For example: (0) Multiple logical nodes of a recursive data structure can be represented as a single physical node, eliminating the need to store pointers between them. For example, an ML implementation can determine that `List.tabulate (n, f)` always creates a list with `n` elements, and thus always pre-allocate a single large enough buffer before actually computing the elements. In Lisp, this wouldn't be a valid optimization, because Lisp mandates that every cons cell has its own object identity. (1) Values with large representations can be automatically deduplicated, hash-consed or whatever it takes to reduce their memory footprint. Again, this is only possible because physical identities don't matter in ML (except for mutable cells and arrays). In other words, values give the language implementation freedom to make useful physical data structure choices. Unlike objects, which come tied to a fixed representation. There is no tradeoff between abstraction and efficiency, when you use the right abstractions.