To Box, or not to Box, that is the question

I'm writing a no-std + alloc library that has some structs with large fields. I want to avoid allocating where possible, but I'm not sure where to draw the line on struct size.

Is there any best practice with regard to boxing individual fields of structs when they get large?

Genrally I follow something like this for fields:
0-100 bytes: No Box
in between: ???
10+ kilobytes: Yes Box

1 Like

I think it depends also on whether you expect the user to move it around a lot. If it’s a singleton-like struct where you only expect the user to have one of it that stays in place (a context struct of sorts), then it can be as large as you want.

4 Likes

Many usages of the library may only create a single instance, but an equally valid usage may have hundreds or more. I'd expect some of the single use cases to be on memory constrained devices (single digit megabytes of RAM), while the multi-instance ones to be on servers with lots of memory.

Well it’s not about the instance count so much as how much it’s destructured and moved around; I only gave the singleton struct as an example. I don’t think there is a definitive guideline here, you just have to think about how it’s used, and respond to benchmarks if necessary.

2 Likes