Reusing values by references

To render a template of an index page, we use a struct with a String field and we have to fill the IndexTemplate struct to call the render method on it. But the template needs an ownership for the value and we have to clone it. Cloning in turn takes time. To avoid this CPU cost, we can use a reference to a value, because if we clone a value that uses a memory heap, we have to allocate a new memory space and copy bytes of the value to a new place.

This is how we can add a reference to a value:

struct IndexTemplate<'a> {
// time: String,
time: &'a str,
}

We have added the 'a lifetime to a struct, because we use a reference inside and the struct that can't live longer than the string value we referred to.

Using references is not always possible for combinations of Future instances, because we have to construct a Future that generates an HttpResponse, but lives longer than calling a handler. In this case, you can reuse a value if you take ownership of it and use methods such as fold to pass the value through all the steps of the combinator's chain. It is valuable for large values, which can consume a lot of CPU time, to be cloned.

Now we can use a reference to the borrowed last_minute value:

// let template = IndexTemplate { time: last_minute.to_owned() };
let template = IndexTemplate { time: &last_minute };

The to_owned method, which we used before, cloned the value that we put to IndexTemplate, but we can now use a reference and avoid cloning at all.

All we need to do now is implement caching, which can help to avoid template rendering.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.176.88