Last active
July 24, 2021 21:25
-
-
Save kYroL01/e60854b2b4dc28586ffcbb1e0c934aea to your computer and use it in GitHub Desktop.
Time calculation of passing slice as a pointer vs as a value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"strconv" | |
"strings" | |
) | |
func track(msg string) (string, time.Time) { | |
return msg, time.Now() | |
} | |
func duration(msg string, start time.Time) { | |
fmt.Printf("%v: %v\n", msg, time.Since(start)) | |
} | |
func addValuePointer(foo *[]string) { | |
defer duration(track("addValue slice")) // func exec time | |
var s strings.Builder | |
for i := 1; i < 50000; i++ { | |
t := strconv.Itoa(i) | |
s.WriteString(t) | |
*foo = append(*foo, s.String()) | |
} | |
} | |
func addValue(foo []string) []string { | |
defer duration(track("addValue slice")) // func exec time | |
var s strings.Builder | |
for i := 1; i < 50000; i++ { | |
t := strconv.Itoa(i) | |
s.WriteString(t) | |
foo = append(foo, s.String()) | |
} | |
return foo | |
} | |
func main() { | |
foo := make([]string, 50, 100) | |
boo := make([]string, 50, 100) | |
foo = []string{"a", "b"} | |
boo = []string{"a", "b"} | |
foo = addValue(foo) | |
//fmt.Println("foo = ", foo) | |
addValuePointer(&boo) | |
//fmt.Println("boo = ", boo) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment