perl - Perl中三元运算符的优化

标签 perl loops optimization ternary-operator

我有这个循环:

for my $line (split /\n/, $content) {
    ($line !~ /^\-{2,}$/) ? ( $return .= "$line\n" )
                          : ( $return .= "\N{ZERO WIDTH SPACE}$line\n" );
}

大部分行与正则表达式不匹配(即:大多数情况下条件为真)。

我首先使用 =~ 运算符(交换了两个条件指令)编写了条件,但这是 second 指令大部分时间都会执行时代。

换句话说……如果您有一个测试,您知道它会在 99% 的情况下选择一个分支,那么首先使用该分支编写它是否会改变某些东西(性能)?

最佳答案

When you have a test which you know that it will choose one branch in 99% of the cases, does it change something (performance) to write it with that branch first?

在简单的 if/else 情况下(即三元运算符),答案是。分支的顺序无关紧要,每次都会运行条件并选择下行的分支。

在 if/elsif/else 情况下,这很重要,因为有多个条件要运行。将最常见的情况放在首位会使事情变得更快。

如果 if/else 选择对读者最有意义的顺序,这通常意味着避免否定。 $line =~/^\-{2,}$/$line !~/^\-{2,}$/ 更易读。 $line =~/^-{2,}$/ 甚至更好(不需要在正则表达式中转义 -)。

至少它不重要。对于任何像 Perl 这样复杂的东西,最好对这些东西进行基准测试。想出一些可以充分锻炼 CPU 的东西,以免在正常的基准测试抖动中丢失,这有点麻烦。在得出结论之前,请务必多次运行此程序并进行大量迭代。

use strict;
use warnings;
use v5.10;

use Benchmark qw(cmpthese);

my $Iterations = shift;

my $Threshhold = 100_000;

# I've picked something that isn't constant to avoid constant folding
sub a_then_b {
    my $num = shift;
    return $num > $Threshhold ? sqrt($num) + sqrt($num) ** 2
                              : $num + $num;
}

sub b_then_a {
    my $num = shift;
    return $num <= $Threshhold ? $num + $num
                               : sqrt($num) + sqrt($num) ** 2;
}

say "First one side";
cmpthese $Iterations, {
    a_then_b => sub { a_then_b($Threshhold - 1) },
    b_then_a => sub { b_then_a($Threshhold - 1) }
};

say "Then the other";
cmpthese $Iterations, {
    a_then_b => sub { a_then_b($Threshhold + 1) },
    b_then_a => sub { b_then_a($Threshhold + 1) }
};

最后要注意的是,要充分利用三元组,赋值应该放在左侧。三元返回其分支的结果。

$return .= $line =~ /^-{2,}$/ ? "\N{ZERO WIDTH SPACE}$line\n"
                               : "$line\n";

关于perl - Perl中三元运算符的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39670180/

相关文章:

c - for循环中嵌套if循环

arrays - 优化从 openCV mat 到 2D float 数组的复制

iphone - 如何减少 iPhone 应用程序的代码大小?

c++ - C++ 编译器中的奇怪行为 - 优化?

python - 正则表达式的最坏情况分析

perl - 在 Moose 中,如何判断一个对象的类是否是另一个对象类的子类?

java - 如何输出代码正在运行的循环的哪一次迭代

c# - 循环遍历 ListView 选中的项目

Perl 使用 XML 路径上下文提取数据

Perlbrew 安装失败