I am new to golang, While doing this poc, I noticed a weird behaviour while running a for loop.
package main;
import (
"log"
"strings"
"time"
)
type data struct {
elapseTime int64
data string
}
func main(){
for i := 0 ; i < 10; i++{
c := make(chan data);
go removeDuplicates("I love oranges LALALA I LOVE APPLES LALALA XD", c);
log.Printf("%v", <- c);
}
}
func removeDuplicates(value string , c chan data){
start := time.Now();
var d = data{};
var r string;
value = strings.ToLower(value);
var m = make(map[string]string);
splitVals := strings.Split(value, " ");
for _, element := range splitVals {
if _, ok := m[element]; ok == false {
m[element] = element;
}
}
for k, _ := range m {
r = r + k + " ";
}
d.data = strings.TrimRight(r, "");
d.elapseTime = time.Since(start).Nanoseconds();
c <- d;
}
Effectively, what I am trying to achieve is to remove duplicates of a simple string and print those information out along with the time taken. a loop runs through a go routine 10 times, waiting for responses to come via the channel.
2019/05/24 00:55:49 {18060 i love oranges lalala apples xd }
2019/05/24 00:55:49 {28930 love oranges lalala apples xd i }
2019/05/24 00:55:49 {10393 i love oranges lalala apples xd }
2019/05/24 00:55:49 {1609 oranges lalala apples xd i love }
2019/05/24 00:55:49 {1877 i love oranges lalala apples xd }
2019/05/24 00:55:49 {1352 i love oranges lalala apples xd }
2019/05/24 00:55:49 {1708 i love oranges lalala apples xd }
2019/05/24 00:55:49 {1268 apples xd i love oranges lalala }
2019/05/24 00:55:49 {1736 oranges lalala apples xd i love }
2019/05/24 00:55:49 {1037 i love oranges lalala apples xd }
Here's what I see: the first few prints of the loop(doesn't matter if its single loop or 100x loop) will be significantly slower than the remainder of the loops. Is there a reason why this is so? (execution time is in nanoseconds btw)
Edit: removing the switch part since people are confused about the question.