What is a zero-cost construction?

or the opposite, what is a NOT a zero-cost construction?
can anyone show me an example? thanks.

extern crate futures;

use std::io;
use std::time::Duration;
use futures::prelude::*;
use futures::future::Map;

// Note here that like iterators, we're returning the `Map` combinator in
// the futures crate, not a boxed abstraction. This is a zero-cost
// construction of a future.
fn add_ten<F>(future: F) -> Map<F, fn(i32) -> i32>
    where F: Future<Item=i32>,
    let add = |a: i32| a + 10;
//    fn add(a: i32) -> i32 { a + 10 }


You likely mean zero cost abstraction - that term lends itself to search/Google, but here is one thread in the past that has some discussion.

1 Like

thanks. I will read the link later.

but here, I want to understand exactly the sentence which I get from the crate example: “This is a zero-cost construction of a future”. what does it mean anyway?

This code will be thrown away by the optimizer during the compilation and thus it shouldn’t have a runtime cost.

1 Like

As @ozkriff mentioned, it basically means all the seeming abstractions here (i.e. the add closure, the future value, the map call to it, etc) is (very likely) optimized away by the compiler and the code would be no different than if you were to write that entire interaction “by hand”, tailor made for that particular example.

So, there’s no memory indirection here and no virtual calls/dynamic dispatch - the compiler sees through your attempts to organize the code into closures, methods, and custom types (i.e. your abstractions cost you “nothing” in terms of runtime cost over doing the same thing with direct handwritten code).


I see, thanks