How many times will len(p) run? Only one and the result will be saved, or will it run for each iteration?
func main() {
p := []int{2, 3, 5, 7, 11, 13}
for i:=0;i<len(p);i++ {}
}
How many times will len(p) run? Only one and the result will be saved, or will it run for each iteration?
func main() {
p := []int{2, 3, 5, 7, 11, 13}
for i:=0;i<len(p);i++ {}
}
len()
on a slice is optimized by the compiler, it's like accessing a local variable. It's not really a function call.
You can verify with:
$ cat x.go package main import "fmt" func main() { a := []int{1,2, 3} fmt.Println(len(a)) }
And then look at the compiler output:
$ go tool 6g -S x.go
--- prog list "main" --- 0000 (x.go:3) TEXT main+0(SB),$128-0 0001 (x.go:4) MOVQ $0,autotmp_0002+-80(SP) 0002 (x.go:4) MOVQ $0,autotmp_0002+-72(SP) 0003 (x.go:4) MOVQ $0,autotmp_0002+-64(SP) 0004 (x.go:4) LEAQ autotmp_0002+-80(SP),BX 0005 (x.go:4) MOVQ BX,autotmp_0001+-56(SP) 0006 (x.go:4) MOVQ autotmp_0001+-56(SP),BX 0007 (x.go:4) MOVQ statictmp_0000+0(SB),BP 0008 (x.go:4) MOVQ BP,(BX) 0009 (x.go:4) MOVQ statictmp_0000+8(SB),BP 0010 (x.go:4) MOVQ BP,8(BX) 0011 (x.go:4) MOVQ statictmp_0000+16(SB),BP 0012 (x.go:4) MOVQ BP,16(BX) 0013 (x.go:4) MOVQ autotmp_0001+-56(SP),BX 0014 (x.go:4) MOVQ $3,CX 0015 (x.go:5) LEAQ autotmp_0005+-16(SP),DI 0016 (x.go:5) MOVQ $0,AX 0017 (x.go:5) STOSQ , 0018 (x.go:5) STOSQ , 0019 (x.go:5) LEAQ autotmp_0005+-16(SP),BX 0020 (x.go:5) MOVQ BX,autotmp_0004+-48(SP) 0021 (x.go:5) MOVQ autotmp_0004+-48(SP),BX 0022 (x.go:5) MOVQ $1,SI 0023 (x.go:5) MOVQ $1,DX 0024 (x.go:5) MOVQ BX,autotmp_0003+-40(SP) 0025 (x.go:5) MOVQ autotmp_0003+-40(SP),BX 0026 (x.go:5) MOVQ $type.int+0(SB),AX 0027 (x.go:5) MOVQ AX,(BX) 0028 (x.go:5) MOVQ CX,8(BX) 0029 (x.go:5) MOVQ autotmp_0003+-40(SP),BX 0030 (x.go:5) MOVQ BX,(SP) 0031 (x.go:5) MOVQ SI,8(SP) 0032 (x.go:5) MOVQ DX,16(SP) 0033 (x.go:5) CALL ,fmt.Println+0(SB) 0034 (x.go:6) RET ,
Notice the CALL to fmt.Println
, but no call to len
.