C ++哪个if / else更快

时间:2018-01-31 17:18:33

标签: c++ if-statement

我见过两种类型的if / else,哪一种更快?

a==b ? cout<<"a" : cout<<"b";

OR

set('hola')==set('loha')

2 个答案:

答案 0 :(得分:4)

三元条件是一种滥用,因为decltype(cout<<"a")是一种可用于三元条件的类型只是巧合:

cout << (a == b ? "a" : "b");

会比if else更容易理解,也可能比static <T> void diff(Iterator<T> lefts, Iterator<T> rights, Comparator<T> comparator, Consumer<T> onlyLeft, Consumer<T> equals, Consumer<T> onlyRight) { while (lefts.hasNext() && rights.hasNext()) { recur(lefts.next(), rights.next(), lefts, rights, comparator, onlyLeft, equals, onlyRight); } if (!lefts.hasNext()) { rights.forEachRemaining(onlyRight); } if (!rights.hasNext()) { lefts.forEachRemaining(onlyLeft); } } static <T> void recur(T left, T right, Iterator<T> lefts, Iterator<T> rights, Comparator<T> comparator, Consumer<T> onlyLeft, Consumer<T> equals, Consumer<T> onlyRight) { if (comparator.compare(left, right) == 0) { equals.accept(left); } else if (comparator.compare(left, right) < 0) { onlyLeft.accept(left); if (lefts.hasNext()) { recur(lefts.next(), right, lefts, rights, comparator, onlyLeft, equals, onlyRight); } else { onlyRight.accept(right); } } else { onlyRight.accept(right); if (rights.hasNext()) { recur(left, rights.next(), lefts, rights, comparator, onlyLeft, equals, onlyRight); } else { onlyLeft.accept(left); } } } public static void main(String[] args) { List<String> tableOne = Lists.newArrayList("1", "2", "3", "4", "5", "6"); List<String> tableTwo = Lists.newArrayList("2", "2", "5", "7", "8"); diff(tableOne.iterator(), tableTwo.iterator(), String::compareTo, left -> System.out.println("Left " + left), both -> System.out.println("Both " + both), right -> System.out.println("Right " + right)); } 更容易处理,否则你应该更清楚。

并相信您的编译器进行优化。如果您有任何疑问,请检查输出组件。

答案 1 :(得分:2)

对你的程序来说,任何一个的表现都不会是灾难性的。

这一切都取决于代码的可读性。

第三级运算符只有一个语句的限制,无论是真还是假。