Skip to content

Commit

Permalink
scope: only loop on the scope once when looking for vars
Browse files Browse the repository at this point in the history
name       old time/op    new time/op    delta
Program-2    1.08ms ± 4%    1.00ms ± 4%  -7.19%  (p=0.000 n=20+20)

name       old alloc/op   new alloc/op   delta
Program-2     239kB ± 3%     239kB ± 3%    ~     (p=0.821 n=18+18)

name       old allocs/op  new allocs/op  delta
Program-2     5.95k ± 3%     5.95k ± 3%    ~     (p=1.000 n=19+19)
  • Loading branch information
ALTree committed Feb 19, 2020
1 parent 83e547b commit 1e17ae0
Showing 1 changed file with 9 additions and 55 deletions.
64 changes: 9 additions & 55 deletions microsmith/scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,97 +237,51 @@ func (ls Scope) GetRandomRangeable(rs *rand.Rand) (Variable, bool) {
// dereferencing pointers).
func (ls Scope) GetRandomVarOfSubtype(t Type, rs *rand.Rand) (Variable, bool) {

cnt := 0
vars := make([]Variable, 0, 32)

for _, v := range ls {
switch v.Type.(type) {

// for structs in scope, we look for fields of type t
case StructType:
for _, ft := range v.Type.(StructType).Ftypes {
if ft == t {
cnt++
vars = append(vars, v)
}
}

// for pointers, we look for the ones having base type t, since we
// can dereference them to get a t Expr
case PointerType:
if v.Type.(PointerType).Base() == t {
cnt++
vars = append(vars, v)
}

// for channels, we can receive
case ChanType:
if v.Type.(ChanType).Base() == t {
cnt++
vars = append(vars, v)
}

// for arrays and maps, we can index
case ArrayType:
if v.Type.(ArrayType).Base() == t {
cnt++
vars = append(vars, v)
}
case MapType:
if v.Type.(MapType).ValueT == t {
cnt++
vars = append(vars, v)
}
case BasicType:
// Can't be used to derive, nothing to do
}
}

if cnt == 0 {
if len(vars) == 0 {
return Variable{}, false
}

rand := 1 + rs.Intn(cnt)
cnt = 0

for _, v := range ls {
switch v.Type.(type) {
case StructType:
for _, ft := range v.Type.(StructType).Ftypes {
if ft == t {
cnt++
if rand == cnt {
return v, true
}
}
}
case PointerType:
if v.Type.(PointerType).Base() == t {
cnt++
if cnt == rand {
return v, true
}
}
case ChanType:
if v.Type.(ChanType).Base() == t {
cnt++
if cnt == rand {
return v, true
}
}
case ArrayType:
if v.Type.(ArrayType).Base() == t {
cnt++
if cnt == rand {
return v, true
}
}
case MapType:
if v.Type.(MapType).ValueT == t {
cnt++
if cnt == rand {
return v, true
}
}
case BasicType:
// Can't be used to derive, nothing to do
}
}

panic("unreachable")
return vars[rs.Intn(len(vars))], true
}

// return a chan (of any subtype). Useful as a replacement of
Expand Down

0 comments on commit 1e17ae0

Please sign in to comment.