can't seem to find any answers to this one. Difficult to word, the code below may explain the idea more succinctly:
x = 5;
// reassigning the same value to the variable - will another write happen?
x = 5
My intuition tells me this may differ by language - I am primarily concerened with PHP.
Thanks!
CodePudding user response:
Assignments are always re-assigned. Checking the current value of a variable requires reading the value, which is another instruction. So on average, you would end up with more instructions.
Consider:
- write - check (identical) - skip = 2 instructions
- write - check (different) - write = 3 instructions
- write - write = 2 instructions
Checking requires reading. Reading is a memory access. Writing is a memory access. Reading from and writing to memory play in the same order of magnitude.
Also, what does "identical" mean? For numbers it might be clear cut, but for objects not so much. Do you want to check recursively every property and nested object of an object or only compare the top level reference?
NB. I am assuming here that there is code executed between the two assignments and they are not happening directly one after another. Compilers/interpreters might catch and unify those and your IDE will definitely flag it.
TLDR: Even if it made a difference, don't worry about such micro-optimizations, they are rarely worth it!