- Home /
Best way to calculate sum of custom object holding numbers and returning sum as that object instance
Ok, so ive created an type Damage, that has a few values and is implementing IEnumerable + has some additional getters, like that:
public class Damage : IEnumerable<float> {
public float v1 = 1;
public float v2 = 2;
public float v3 = 3;
[...]
}
Instances of that class are assigned to game objects. Then i have controller, that calculates sum of Damages for every game object. There is problem, because i suppose i need high performence solution here, because ill be calling that sum in every iteration. I have thought of 2 ways doing that:
public class Controller : MonoBehaviour {
[...]
public Damage GetSum1() {
float v1 = 0;
float v2 = 0;
float v3 = 0;
foreach (Damage damage in gameObjectList) {
v1 += damage.v1;
v2 += damage.v2;
v3 += damage.v3;
}
return new Damage (v1, v2, v3);
}
private Damage damageSum = new Damage();
public Damage GetSum2() {
damageSum.v1 = 0;
damageSum.v2 = 0;
damageSum.v3 = 0;
foreach (Damage damage in gameObjectList) {
damageSum.v1 += damage.v1;
damageSum.v2 += damage.v2;
damageSum.v3 += damage.v3;
}
return damageSum;
}
}
And now lets analyze those solutions: GetSum1 - im afraid of allocating memory in every single Update iteration. That one can lead to enormouse memory usage. Its bad. Advantage is that i can make my Damage class immutable, which is more secure than mutable version. GetSum2 - with this solution i have to make Damage class mutable, which is less defensive, but it has much better performance, since i dont need to allocate new object in every single iteration.
I thought also about another solution - making Damage structure instead of class and than use first way. Why i thought about it ? Because i dont know how struct works. I know that structs are called "value types", so i thought they may be kind of like primitive types. Am I wrong ? Calling new Damage(v1, v2, v3) would be as optimal as creating just 3 floats inside a loop ?
Does this code even run? If it does can't you just do public int Sum(){ return v1+v2+v3;} ?
The whole point of creating Damage class is to separate those damage value parts and keep them close together in one single "dataset". What would be point of getting sum of them ? Why would i need an class ins$$anonymous$$d of using simple number in such case ?
Your answer
Follow this Question
Related Questions
Struct for holding Class Parameters 0 Answers
(Solved) What is done in preloading ( Application.LoadLevel(x) ) 2 Answers
UI-based game memory and performance issue. 1 Answer
Lists and Structs instead of Arrays? 4 Answers
Memory Managmenet 1 Answer