zoukankan      html  css  js  c++  java
  • 关于print函数的一些细节问题探讨

    在论坛看了一些别人的代码,经常会用到print函数来打印指定的字符串,有一些需要在末尾打印换行符,但是我看到了三个不同的版本:
    一、

    my $var='hello,world';
    print "$var\n";

    二、

    my $var='hello,world';
    print $var , "\n";

    三、

    my $var='hello,world';
    print $var . "\n";

    想问一下这三种方式有什么区别吗?比如在效率和内部处理方面?

    use strict;
    use warnings;
    use File::Spec;
    use Benchmark;

    my $str = 'Hello, World' x 1000000;
    open(NULL, ">", File::Spec->devnull);
    timethese(100, {
        'print $str, "\n"'  => sub { print NULL $str, "\n"},
        'print "$str\n"'    => sub { print NULL "$str\n"},
        'print $str . "\n"' => sub { print NULL $str . "\n"},
    });

    # Windows上跑的, 结果如下:
    # Benchmark: timing 100 iterations of print "$str\n", print $str . "\n", print $str, "\n"...
    # print "$str\n": 14 wallclock secs (12.46 usr +  0.18 sys = 12.64 CPU) @  7.91/s (n=100)
    # print $str . "\n": 15 wallclock secs (12.60 usr +  0.18 sys = 12.78 CPU) @  7.83/s (n=100)
    # print $str, "\n": 11 wallclock secs (10.45 usr +  0.12 sys = 10.57 CPU) @  9.47/s (n=100)
    # 比较明显的是print $str, "\n"最快, 而其余2种方法不相上下(多次测试中这2种各有快慢, 可忽略差异).

    简单分析下:
    print $var, "\n" 直接输出
    print "$var\n" 内部生成新变量, 再输出
    print $var . "\n" 同上


  • 相关阅读:
    python模块学习第 0000 题
    报错The VMware Authorization Service is not running
    图像指纹的重复识别
    CSS预编译器配置-------LESS Sass Stylus webstorm
    CSS布局中的水平垂直居中
    进度与日程
    HTML5 application cache
    进度
    CC2530芯片介绍
    Linux命令工具 top详解
  • 原文地址:https://www.cnblogs.com/fpga/p/1628486.html
Copyright © 2011-2022 走看看