Is it okay to clone() often in a REST API?

85 points Barbacamanitu00

I've been building a REST API using axum lately. I have various POD structs that get passed around and converted to and from each other. For example, I have a struct Foo with fields a and b, both of which are Strings. I also have a struct Bar with fields a,b, and also all Strings. There's other structs containing Vecs of Foo and Bar.

These are all serialized and deserialized. Sometimes they represent a request object, and sometimes they represent a response object.

These structs all contain only owned values. When I convert from Foo to Bar, I clone a and b from Foo to populate the fields of Bar, then generate c based on a and b. There's a few spots where I clone entire Vecs of structs from one type to another.

Is this a problem at all? My api seems to only take a couple milliseconds to complete a request, and the objects cloned from are dropped at the end of the request handler. It may not be super Rusty to clone everywhere, but since this data is all POD and needs to be Json serialized, I feel like owned data makes sense and simplifies things.

Am I missing anything by using only owned Strings and clones? Since all the cloned from values are dropped during the course of a single request handler, shouldn't memory usage be minimized too? Another benefit seems to be that my data structures never need to be mut, and I have pretty fine grained control of the data via my types. For example, i have a Foo and FooUnique, where the unique version has a uuid field in the top level and all child structs. Foo is generated from making an external API request, but before saving to my database I need to create a uuid for every field.

To me, encoding this information in the type system makes sense since I can't try go save a Foo to my database. My database functions only deal with FooUnique. Again, my From<Foo> for FooUnique simply clones all the fields from Foo and then generated a uuid.