Неэффективно ли перевернуть строку с помощью цикла for в golang? - PullRequest
0 голосов
/ 05 июня 2019

Я сделал это так, Голанг:

func reverseStr(str string) string {
    var reversed string

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

    return reversed
}

Я новичок и пока не могу добиться большего, но я все еще учусь.Я хотел бы знать, является ли мой метод менее эффективным, чем те, которые я видел в Интернете, которые используют руны:

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)
}

1 Ответ

3 голосов
/ 05 июня 2019

Я хотел бы знать, что мой метод менее эффективен, чем те, которые я видел в Интернете, использующие руны

Ничего общего с рунами или циклом for.Ваш метод строит и перестраивает и перестраивает строку снова и снова.В то время как другой переворачивает строку на месте, просто меняя символы.И разница только увеличивается с большими строками.

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.")
    }
}

Результаты

$ 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...