Question: I argued with a friend the other day about those two snippets. Which is faster and why ?

```
value = 5;
if (condition) {
    value = 6;
}

```

and:

```
if (condition) {
    value = 6;
} else {
    value = 5;
}

```

What if `value` is a matrix ?

Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option.

**Edit** (requested by staff since question is on hold at the moment):

* please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*.
* when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)

Answer: 
The answer from [CompuChip](https://stackoverflow.com/a/43202221/2805305) shows that for `int` they both are optimized to the same assembly, so it doesn't matter.

> 
> What if value is a matrix ?
> 
> 
> 

I will interpret this in a more general way, i.e. what if `value` is of a type whose constructions and assignments are expensive (and moves are cheap).

then

```
T value = init1;
if (condition)
   value = init2;

```

is sub-optimal because in case `condition` is true, you do the unnecessary initialization to `init1` and then you do the copy assignment.

```
T value;
if (condition)
   value = init2;
else
   value = init3;

```

This is better. But still sub-optimal if default construction is expensive and if copy construction is more expensive then initialization.

You have the conditional operator solution which is good:

```
T value = condition ? init1 : init2;

```

Or, if you don't like the conditional operator, you can create a helper function like this:

```
T create(bool condition)
{
  if (condition)
     return {init1};
  else
     return {init2};
}

T value = create(condition);

```

Depending on what `init1` and `init2` are you can also consider this:

```
auto final_init = condition ? init1 : init2;
T value = final_init;

```

But again I must emphasize that this is relevant only when construction and assignments are really expensive for the given type. And even then, only by **profiling** you know for sure.
In unoptimised code, the first example assigns a variable always once and sometimes twice. The second example only ever assigns a variable once. The conditional is the same on both code paths, so that shouldn't matter. In optimised code, it depends on the compiler.

As always, if you are that concerned, generate the assembly and see what the compiler is actually doing.