duanlaiyin2356 2016-01-17 11:28
浏览 152
已采纳

len(string)== 0或len(string)<1

In Go, to check if a string is empty this can be used:

len(str) == 0

or

len(str) < 1

or

str == ""

Basically is just a meter of choosing an operator ==, <, !=, but in terms of performance wish option is better ?

My guess is that == just compares and don't iterate through the values like < or either <== could do, therefore wondering what is the best approach practice for this.

  • 写回答

2条回答 默认 最新

  • dougai0138 2016-01-17 11:41
    关注

    Since the empty string is the nil value of a string, you should compare against that.

    str == ""
    

    Checking variables against their nil values to see if they are empty is the Go way of doing this.

    In terms of performance, there's no notable difference. Using len(str) is a function call, so it should in theory be slower.

    EDIT: Some evidence:

    I benchmarked this code:

    func BenchmarkNil(b *testing.B) {
        str := "asd"
        cnt := 0
        for i := 0; i < b.N; i++ {
            if str == "" {
                cnt++
            }
        }
    }
    

    with the three different checks in the if-statement: str == "", len(str) == 0 and len(str) < 1.

    BenchmarkLenEq-8        2000000000               0.77 ns/op
    BenchmarkLenLess-8      2000000000               0.76 ns/op
    BenchmarkNil-8          2000000000               0.50 ns/op
    

    For checking against an empty string (str := "" instead of str := "asd"), there is no measurable difference. Checking against a non-empty string takes more time, and there, the nil check is noticeably faster.

    BenchmarkLenEq-8        2000000000               0.34 ns/op
    BenchmarkLenLess-8      2000000000               0.33 ns/op
    BenchmarkNil-8          2000000000               0.33 ns/op
    

    EDIT2: The only thing you can do these days to be somewhat sure of how fast something is is to benchmark it. Modern CPU's are superscalar, so one clock cycle per instruction is simply not true anymore. The benchmark code comparing against the empty string ran at 2.94GHz (2.94*10^9 op/s) on my 4GHz 6700k, which is less than two clock cycles per loop iteration. The nil check against the non-empty string ran at 2GHz (2*10^9 op/s) on the same CPU.

    This means 2 cpu cycles per loop iteration on the nil check, and 3 on the len check, or a single instruction per loop iteration on the check against the empty string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow