更好地比较片或字节? [英] Better to compare slices or bytes?

查看:55
本文介绍了更好地比较片或字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道哪种方法更好(或者是否缺少更好的方法).我正在尝试确定一个单词的第一个字母和最后一个字母是否相同,并且有两个明显的解决方案.

I'm just curious on which of these methods is better (or if there's an even better one that I'm missing). I'm trying to determine if the first letter and last letter of a word are the same, and there are two obvious solutions to me.

if word[:1] == word[len(word)-1:]

if word[0] == word[len(word)-1]

据我所知,第一个只是提取字符串的一部分并进行字符串比较,而第二个则是从任一端提取字符并将其作为字节进行比较.

As I understand it, the first is just pulling slices of the string and doing a string comparison, while the second is pulling the character from either end and comparing as bytes.

我很好奇两者之间是否存在性能差异,并且是否有任何可取的"方式来做到这一点?

I'm curious if there's a performance difference between the two, and if there's any "preferable" way to do this?

推荐答案

如果用字母表示,您的意思是符文,然后使用:

If by letter you mean rune, then use:

func eqRune(s string) bool {
    if s == "" {
        return false // or true if that makes more sense for the app
    }
    f, _ := utf8.DecodeRuneInString(s)  // 2nd return value is rune size. ignore it.
    l, _ := utf8.DecodeLastRuneInString(s) // 2nd return value is rune size. ignore it.
    if f != l {
        return false
    }
    if f == unicode.ReplacementChar {
        // First and last are invalid UTF-8. Fallback to 
        // comparing bytes.
        return s[0] == s[len(s)-1]
    }
    return true
}

如果您指的是字节,请使用:

If you mean byte, then use:

func eqByte(s string) bool {
    if s == "" {
        return false // or true if that makes more sense for the app
    }
    return s[0] == s[len(s)-1]
}

比较另一个字节比比较基准测试中显示的字符串切片要快.

Comparing individual bytes is faster than comparing string slices as shown by the benchmark in another answer.

游乐场示例

这篇关于更好地比较片或字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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