- Home /
How of these two methods are more efficient?
public int num; //The value will change
int numCopy;
void Update ()
{
//method 1
if (numCopy != num)
{
numCopy = num;
}
//method 2
numCopy = num;
}
Answer by Cornelis-de-Jager · Jan 09, 2019 at 12:52 AM
In all cases Method Two.
lets talk about memory access Cycles within an computer. When a computer access the memory for performing an operation it will run through the entire memory linearly to find all the required data procedurally. For example when loading a simple class it can take up to 300 cycles, because a class is not stored linearly in memory, its scattered. Compare this to a struct which is stored linearly and would take les than 10 cycles.
Now I believe primitives can be accessed within one cycle, if not it would not matter in this scenario anyway, but it means that checking for "if" condition first then assigning can take 2 cycles or in somecases 1 if stored correctly. Meaning it can possibly double the computational power needed.
However, the computational power difference or needed to perform either of these two operation is so insignificant its not worth looking into it. (because they are primitives) Usually if there are performance issues there are allot other issues you solve first.
Hope this helps
Answer by Tobychappell · Jan 08, 2019 at 11:21 PM
Without knowing use case and any other parts of your code Method2 is more efficient (if efficiency is based on number of instructions), because both will want to end up having those two integers having the same value, therefore the if condition is unnecessary.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Pooling Efficiency Transform vs gameObject 0 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Does This Make Sense? Is It Correct? 2 Answers