Concatenate strings in "golang"

Intercloud.Feb 08, 2019

A quick benchmark

InterCloud is a private network physically connected to all major cloud providers that provides secure and performant connectivity to multinationals.

We provide our customer with a web Portal that allows service KPIs' visualisation, like bitrate, latency or jitter.

Introduction

When I begun entering golang code bases with developers of various seniority levels, I was surprised to see many ways of doing join strings. Making "onetwo" out of one and two is used a lot in any programming language.

I decided to do a quick benchmark. Comming from the C/C++ world, the result in golang surprized me (in a good way).

The origin

Let's do it in a C maner using Sprintf.

I use pointers here to simulate the fact that we are in a function.

#include <stdlib.h>
#include <stdio.h>

int main(){
    char str[] = "my_string";
    char *s = malloc(sizeof(str) + sizeof(str));
    sprintf(s, "my_string%s", str);
    printf("%s\n", s);
}

Let's go golang

Let's do like in C. This was (at least when I begin with golang) a instinctive way for me.

package main

import "fmt"

func main() {
    str := "my_string"
    fmt.Println(fmt.Sprintf("my_string%s", str))
}

Let's try an other way strings.Join

Discussing with others I realize that strings.Join is quite popular.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "my_string"
    fmt.Println(strings.Join([]string{"my_string", str}, ""))
}

Let's try C++ way using strings.Builder

Having experienced string builder in C++ and Java I thought I could give it a try.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "my_string"
    var b strings.Builder
    b.WriteString("my_string")
    b.WriteString(str)
}

Let's try Cpp way using +

Plus is kind of obvious but does not feel smart.

package main

import "fmt"

func main() {
    str := "my_string"
    fmt.Println("my_string" + str)
}

InterCloud

InterCloud’s end-to-end global connectivity platform eliminates the complexity in deploying the cloud, giving businesses full control over the security, sovereignty and performance of their critical data traffic with complete peace of mind.

Working with organisations to help them transform global connectivity, reduce network complexity and accelerate growth and innovation, InterCloud is a trusted advisor to some of the world's leading brands when it comes to leveraging the cloud for future success

With offices across Europe, the company's platform is underpinned by its team of cloud experts who guide customers to implement effective strategies to leverage the power of the cloud across their organisation – making global connectivity a driver for business performance .

www.intercloud.com

Solve your cloud connectivity challenges today