-
Adding int to long long
Supposed I do the following:
b= b + a;
, where b is a long long variable and a is an int variable
Will the compiler do any type casting which is expensive? Does this depend on the compiler?
Should I initially declare "a" as a long long to improve the speed? In my situation, always speed over memory and I am using gcc .
Thanks.
-
The only real answer is: "Profile both and use which ever is faster"
It depends on ... stuff.
Say for example it happens to be faster having both types the same on a certain platform, and where there is only one of 'a'. Then if 'a' is actually an array of 1000s of values you'll probably find that using ints is faster due to there being less memory usage.
Processors are too complicated nowdays to calculate accurate run-times even by directly adding up a number of clocks specified for each machine instruction. You sure as hell can't always predict which is faster at the high-level-language level.
Besides, this almost certainly wont be your bottleneck. If it was you're bottlenenk then that would mean you've already determined this by profiling, in which case you already know the answer.
You've better off posting a snippet with surrounding code, and someone can probably give you a really effective optimisation that you'd probably never dream of.
-
The standards require that the compiler will logically convert a to long long, add that to b, and store the result in b.
However, the standards allow compilers wriggle room around the point where I used the word "logically". Essentially the required observable effect of the statement is that b will end up containing the value computed as b+a. And, compilers, are free to implement that in any way that makes sense.
I suggest that, if speed is that important to you, you profile and measure performance for various alternatives, and pick the way that meets your requirement. In practice, I anticipate you will find no significant variation between alternatives.
My personal view (which I suspect is consistent with iMalc's post) is that you're doing premature optimisation. Basic operations like an integer addition don't tend to be performance critical, and are rarely worth the effort of optimising by hand. You will get more benefit by analysing and profiling significant functions in your code (eg algorithms) to identify the performance hot spots, rather than optimising single operations.