Hacker News new | ask | show | jobs
by lmilcin 1859 days ago
Well... the only language with true zero-cost abstractions is Lisp (assuming you call it a language, which it strictly isn't, but let's not go there right now).

The reason Lisp is zero cost is because what you write as data structure (the program IS a data structure) can be interpreted however you decide it to be interpreted. You can design any kind of abstraction you like and then separately completely control how that code is translated to binary.

For example, when you write a function call like printf("%d", 7) in C (forgetting built in optimization for printf...), the resulting binary has no other choice than to call printf function, parse "%d" and then conditionally read in argument and create a string.

On the other hand if C was Lisp it could, at the time of compilation, translate this code to invocation of putc('7') so that during normal execution the parsing of "%d" would never happen.

In C this requires compiler support. In Lisp you are compiler -- you decide what code is going to be generated.

1 comments

"Zero cost abstraction, for some definition of cost" :-)
Well, yes. In that case every abstraction costs because at the very least you need to develop it and it costs.

I think there are two major contributors to cost of abstraction.

#1 is performance. Does it add stuff that is not strictly necessary but is just side effect of abstraction mechanism? Does it affect memory layout to be less than ideal? Does it prevent generated code to be ideal?

#2 is leaks. Leaks are cost. Leak is when the user of abstraction needs to be aware of more details than just the official abstraction. For example, regular expression is a leaky abstraction because, except for simple regexes, you need to know a lot about actual implementation of the regex so that you understand how to write so that it does not require infinite memory and finishes before heat death of the Universe.

Traditionally, "zero-cost" refers to #1 and I think this is very useful definition.

It is difficult to impossible to prevent #2. Using #1 as definition of zero-cost describes tools with which you can use to create your solution without hampering your performance (significantly). These tools do not need to be simple or even intuitive (and Rust is neither).