I don’t know how to type this in to google, so I’m asking this here.
In programming, do operators take different amounts of time or CPU usage? For example would:
x = y + z
take less amount of time/CPU than:
x = y * z
?
I know it is not noticeable, if at all. Just a curious question.
Also, if you could include as many operators as possible such as +=, -=, *=, and /= along with all normal operators.
Thank you!
There is no master list for all languages, data types, CPUs, and so on, because there is just too much variability.
In some languages, operators are just syntactic sugar for full dynamically-determined type-dispatched function calls, so “a + b” could wind up being a complicated function call that takes minutes, while “a * b” might be a simple function call that takes milliseconds—or vice versa.
In languages that have fixed, compile-time types (including C++ as well as C even though C++ has overloading), you can determine at compile-time what’s going to get invoked, which helps pin things down a lot, but still does not give you a final answer. (See also Dan D and Alex’s answers.)
“Augmenting operators” (+= and so on) are usually just shorthand for assignment-after-expanded-operation. The actual operation takes the same amount of time. In languages with dynamic type dispatch, sometimes you cut off some auxiliary (non-operator) work as well since the augmenting operation need only look up the type of the variable once. With static (compile-time) typing, as long as the compiler is reasonably smart, simple
a += btype operations never save anything overa = a + bat runtime, they are just easier to read. More complicated cases, likep->q->r->s += t, can actually save time since (in tricky cases) thep->q->r->sevaluation has to be done repeatedly if it’s written out repeatedly.As for the underlying CPU operations, there are some rules of thumb, but you have to haul out the appropriate CPU manuals to see which ones apply:
These kinds of things make writing modern compiler-optimizers pretty tricky. 🙂