Question

Is it bad practice to initialize and do arithmetic within a variable? i.e say I have multiple rooms of different area dimensions that I must find the area of:

(example in feet)

double room_area1 = 9.5 * 6.8;
double room_area2 = 9.1 * 6.2;
double room_area3 = 10.0 * 7.1; 

Or is it best to do:

double room_area1 = 9.5;
room_area1 = room_area1 * 6.8;

Is there any disparity between the two ways here or is it the same thing and just a matter of style?

Was it helpful?

Solution

First involves only one operation: Initialization,
While second involves two operations: Initialization + Assignment.

For an intrinsic data type like double the overhead is negligible but for user defined data types second is detrimental to performance(How much? Profiling should tell that).

So in general it is better practice to use First because:

  • It is guaranteed to be atleast as fast if not faster than Second
  • It is more readable.

OTHER TIPS

The first way is better. Reason: it's more readable.

While it is correct, that these constructions are semantically different, for simple types the compiler will almost certainly optimize the second case to be like the first case, and generate the same machine code, storing a constant (calculated at compile-time) into room_area1.

There's nothing wrong with the first examples. In fact it's better that way because you can declare the variable const.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top