三元运算符与if语句的漂亮 [英] Prettiness of ternary operator vs. if statement

查看:111
本文介绍了三元运算符与if语句的漂亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览一些代码,我发现了一些三元运算符。这段代码是我们使用的一个库,它应该非常快。

I'm browsing through some code and I found a few ternary operators in it. This code is a library that we use, and it's supposed to be quite fast.

我在想除了那里的空间外什么都要保存。

I'm thinking if we're saving anything except for space there.

您有什么经历?

推荐答案

表现



如果 / 其他不同>声明......他们可能会解析为抽象语法树中的相同表示,进行相同的优化等。

Performance

The ternary operator shouldn't differ in performance from a well-written equivalent if/else statement... they may well resolve to the same representation in the Abstract Syntax Tree, undergo the same optimisations etc..

如果您正在初始化常量或引用,或者计算出在成员初始化列表中使用哪个值,则如果 / else 语句不能用于 可以是:

If you're initialising a constant or reference, or working out which value to use inside a member initialisation list, then if/else statements can't be used but ? : can be:

const int x = f() ? 10 : 2;

X::X() : n_(n > 0 ? 2 * n : 0) { }



简明代码的保理



键使用的原因? 包括本地化,并避免冗余地重复相同语句/函数调用的其他部分,例如:

Factoring for concise code

Keys reasons to use ? : include localisation, and avoiding redundantly repeating other parts of the same statements/function-calls, for example:

if (condition)
    return x;
else
    return y;

...仅优于......

...is only preferable to...

return condition ? x : y;

...如果处理非常缺乏经验的程序员,或者某些条款足够复杂,可读性方面...... 结构在噪音中丢失了。在更复杂的情况下,例如:

...on readability grounds if dealing with very inexperienced programmers, or some of the terms are complicated enough that the ? : structure gets lost in the noise. In more complex cases like:

fn(condition1 ? t1 : f1, condition2 ? t2 : f2, condition3 ? t3 : f3);

等值如果 / else

if (condition1)
    if (condition2)
        if (condition3)
            fn(t1, t2, t3);
        else
            fn(t1, t2, f3);
    else if (condition3)
            fn(t1, f2, t3);
        else
            fn(t1, f2, f3);
else
    if (condition2)
       ...etc...

这是很多额外的函数调用,编译器可能会或可能不会优化掉。

That's a lot of extra function calls that the compiler may or may not optimise away.

如果表达式 t1 f1 t2 等过于冗长而无法重复输入,创建命名临时值可能有所帮助,但随后:

If the expressions t1, f1, t2 etc. are too verbose to type repeatedly, creating named temporaries may help, but then:


  • 要获得性能匹配 您可能需要使用 std :: move ,除非将相同的临时值传递给名为的函数中的两个&& 参数,然后您必须避免它。这更复杂且更容易出错。

  • To get performance matching ? : you may need to use std::move, except when the same temporary is passed to two && parameters in the function called: then you must avoid it. That's more complex and error-prone.

c x y 评估 c 然后 x y ,这使得在使用它之前测试指针不是 nullptr 是安全的,同时提供一些回退值/行为。该代码仅获得实际选择 x y 中的任何一项的副作用。使用命名临时对象,如果 / 其他 c> 在初始化过程中执行不需要的代码,或者代码执行的次数超出预期。

c ? x : y evaluates c then either but not both of x and y, which makes it safe to say test a pointer isn't nullptr before using it, while providing some fallback value/behaviour. The code only gets the side effects of whichever of x and y is actually selected. With named temporaries, you may need if / else around or ? : inside their initialisation to unwanted code executing, or code executing more often than desired.

考虑:

void is(int) { std::cout << "int\n"; }
void is(double) { std::cout << "double\n"; }

void f(bool expr)
{
    is(expr ? 1 : 2.0);

    if (expr)
        is(1);
    else
        is(2.0);
}

在上面的条件运算符版本中, 1 经历标准转换为 double ,以便匹配 2.0 的类型,意味着是(double)即使对于 true / 1 情况,也会调用重载。 if / else 语句不会触发此转换: true / 1 分支电话是(int)

In the conditional operator version above, 1 undergoes a Standard Conversion to double so that the type matched 2.0, meaning the is(double) overload is called even for the true/1 situation. The if/else statement doesn't trigger this conversion: the true/1 branch calls is(int).

您不能在条件运算符中使用总体类型为 void 的表达式,而它们在下的语句中有效,如果 / else

You can't use expressions with an overall type of void in a conditional operator either, whereas they're valid in statements under an if/else.

有一个不同的重点:

一个如果 / else 语句首先强调分支,然后要做的是次要的,而三元运算符强调要对要做的值的选择要做什么它带有。

An if/else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.

在不同情况下,要么更好地反映程序员对代码的自然观点,又要更容易理解,验证和维护。根据您在编写代码时考虑这些因素的顺序,您可能会发现自己选择了一个 - 如果您已经启动做某事,那么发现您可能会使用几个(或几个)值中的一个来做它与 是表达最少的破坏性方式并继续编码流程。

In different situations, either may better reflect the programmer's "natural" perspective on the code and make it easier to understand, verify and maintain. You may find yourself selecting one over the other based on the order in which you consider these factors when writing the code - if you've launched into "doing something" then find you might use one of a couple (or few) values to do it with, ? : is the least disruptive way to express that and continue your coding "flow".

这篇关于三元运算符与if语句的漂亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆