dougeqiang1619 2019-06-05 19:25
浏览 103
已采纳

通过在golang中使用for循环来反转字符串效率低下?

I did it like this Golang:

func reverseStr(str string) string {
    var reversed string

    for i := len(str) - 1; i >= 0; i-- {
        reversed += string(str[i])
    }

    return reversed
}

I'm a beginner and can't do better for now, but I'm still learning. I'd like to know is my method less efficient than the ones I saw online that use runes:

func reverse(s string) string {
    chars := []rune(s)
    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
        chars[i], chars[j] = chars[j], chars[i]
    }
    return string(chars)
}
  • 写回答

2条回答 默认 最新

  • duangang4001 2019-06-05 20:05
    关注

    I'd like to know is my method less efficient than the ones I saw online that use runes

    Nothing to do with runes or for loop. Your method builds and rebuilds and rebuilds a string, over and over. Whereas the other one reverses the string in-place, by simply swapping characters. And the difference is only getting worse with larger strings.

    package main
    
    import "testing"
    
    func reverseConcat(str string) string {
        var reversed string
    
        for i := len(str) - 1; i >= 0; i-- {
            reversed += string(str[i])
        }
    
        return reversed
    }
    
    func reverseSwapRunes(s string) string {
        chars := []rune(s)
        for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
            chars[i], chars[j] = chars[j], chars[i]
        }
        return string(chars)
    }
    
    func BenchmarkConcatSmall(b *testing.B) {
        for i := 0; i < b.N; i++ {
            reverseConcat("hello world")
        }
    }
    
    func BenchmarkSwapRunesSmall(b *testing.B) {
        for i := 0; i < b.N; i++ {
            reverseSwapRunes("hello world")
        }
    }
    
    func BenchmarkConcatLarger(b *testing.B) {
        for i := 0; i < b.N; i++ {
            reverseConcat("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.")
        }
    }
    
    func BenchmarkSwapRunesLarger(b *testing.B) {
        for i := 0; i < b.N; i++ {
            reverseSwapRunes("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.")
        }
    }
    

    Results

    $ go test -bench . -benchmem
    goos: linux
    goarch: amd64
    BenchmarkConcatSmall-8           5000000           329 ns/op          80 B/op         10 allocs/op
    BenchmarkSwapRunesSmall-8       20000000           117 ns/op          16 B/op          1 allocs/op
    BenchmarkConcatLarger-8            30000         44877 ns/op      172833 B/op        573 allocs/op
    BenchmarkSwapRunesLarger-8        300000          5353 ns/op        2944 B/op          2 allocs/op
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog