Hey guys, I had some questions about putting f
next to literal values. I know it defines it as a float
but do I really need it?
Is this 2.0f * 2.0f
any faster then 2.0 * 2.0
? and if I have a variable like float a = 2.0;
is this 2.0f * a
any faster then 2.0 * a
?
views:
170answers:
3I's rarely about speed (at least directly), but the fact that otherwise the compiler will warn about converting double
to float
.
Sometimes you need it to explicitly have type float
, like in the following case
float f = ...;
float r = std::max(f, 42.0); // won't work; (float, double).
float r = std::max(f, 42.0f); // works: both have same type
AFAIK, on "normal" PCs (x86 with x87-like mathematical coprocessor) the difference in speed is irrelevant, since the calculations are internally done anyway in 80-bit precision.
Floats may gain importance when you have large arrays of floating-point numbers to manage (scientific calculations or stuff like that), so having a smaller data type may be convenient, both to use less memory and to be faster to read them from RAM/disk.
It may also be useful to use floats instead of doubles on machines that lack a floating point unit (e.g. most microcontrollers), where all the floating-point arithmetic is performed in software by code inserted by the compiler; in this case, there may be a gain in speed operating on floats (and in such environments often also every bit of memory matters).
On PCs, IMO you can just use double in "normal" contexts, just try to avoid mixing datatypes (double, floats, ints, ...) in the same expression to avoid unnecessary costly conversions. Anyhow, with literals the compiler should be smart enough to perform the conversion at compile time.