We use primitive types without considering constructors and destructors. It may be because of that, most of them are stored in the stack. We also use struct
like float3
for primitive types. We may also make the same for classes. At the beginning of a function, create a new instance, use it and release the memory at the end of the function.
Instead of using a local variable, if we declared an instance variable at the class level, the variable will exist until the class that holds it is released. This increases the steady memory usage. Further, there should be some update methods that are forwarded to this instance. For example, changing container size may affect the content, so a new size should be forwarded to them.
How should a class keep a reference to a variable to avoid creating the variable numerous times?
I know it is related to the number of times its constructor (or destructor) is called, but I am looking for a general solution. Such as, if the class contains only primitives like x, y, z and they are immutable you should construct them always etc.
A way of deciding which way to choose, making float3
immutable or making its x, y, and z modifiable.
If you use primitive types, there is likely no difference.
If you use objects of some more "complicated" types, you will probably have to reset it to a known state before reusing it. This might take at least as much code as creating a new object. It also complicates your code, which is never an advantage.
Unless you notice a particular bottleneck in your code, you should try to keep it simple and easy to read. Don't complicate things until you absolutely have to.