Home >Backend Development >Golang >How to splice string arrays in golang

How to splice string arrays in golang

尚
Original
2020-01-14 09:47:195985browse

How to splice string arrays in golang

Use the strings.Join() method to splice string arrays:

func BenchmarkAddStringWithJoin(b *testing.B) {
    hello := "hello"
    world := "world"
    for i := 0; i < b.N; i++ {
        _ = strings.Join([]string{hello, world}, ",")
    }
}

join will first calculate the length after splicing based on the contents of the string array, and then Apply for memory of the corresponding size and fill in the strings one by one. If there is already an array, this efficiency will be very high, but if there is not already, the cost of constructing this data is not small.

This method is similar to the Array.prototype.join method in js. It splices a target string into each element of the array. The target string is the parameter of the join method.

strings The .Join method is more efficient than ordinary string splicing in the form of "str" ​​or "str2". This is because the string itself is a constant. To splice it into a new string, the original string object must be destroyed and then used. The current reference points to a new string object, which is very expensive, but strings.Join does not.

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of How to splice string arrays in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn