Skip to content

Commit

Permalink
Optimize slice memory allocations at different places: (istio#26550)
Browse files Browse the repository at this point in the history
Avoid unwanted memory allocations by setting capacity for slices
as length whenever length is known to create accurate size array to
back it. It is already handled in many places in the code and missed
in few. Hence, this commit fixes it.

Signed-off-by: Aliasgar Ginwala <aginwala@ebay.com>
  • Loading branch information
noah8713 authored Aug 24, 2020
1 parent ef21054 commit 8dfaf33
Show file tree
Hide file tree
Showing 14 changed files with 27 additions and 26 deletions.
8 changes: 4 additions & 4 deletions istioctl/cmd/add-to-mesh.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,6 @@ func injectSideCarIntoDeployment(client kubernetes.Interface, deps []appsv1.Depl
}

func findDeploymentsForSvc(client kubernetes.Interface, ns, name string) ([]appsv1.Deployment, error) {
deps := make([]appsv1.Deployment, 0)
svc, err := client.CoreV1().Services(ns).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return nil, err
Expand All @@ -368,6 +367,7 @@ func findDeploymentsForSvc(client kubernetes.Interface, ns, name string) ([]apps
if err != nil {
return nil, err
}
deps := make([]appsv1.Deployment, 0, len(deployments.Items))
for _, dep := range deployments.Items {
depLabels := k8s_labels.Set(dep.Spec.Selector.MatchLabels)
if svcSelector.Matches(depLabels) {
Expand Down Expand Up @@ -481,15 +481,15 @@ func generateServiceEntry(u *unstructured.Unstructured, o *vmServiceOpts) error
if o == nil {
return fmt.Errorf("empty vm service options")
}
ports := make([]*v1alpha3.Port, 0)
ports := make([]*v1alpha3.Port, 0, len(o.PortList))
for _, p := range o.PortList {
ports = append(ports, &v1alpha3.Port{
Number: uint32(p.Port),
Protocol: string(p.Protocol),
Name: p.Name,
})
}
eps := make([]*v1alpha3.WorkloadEntry, 0)
eps := make([]*v1alpha3.WorkloadEntry, 0, len(o.IP))
for _, ip := range o.IP {
eps = append(eps, &v1alpha3.WorkloadEntry{
Address: ip,
Expand Down Expand Up @@ -528,7 +528,7 @@ func resourceName(hostShortName string) string {
}

func generateK8sService(s *corev1.Service, o *vmServiceOpts) {
ports := make([]corev1.ServicePort, 0)
ports := make([]corev1.ServicePort, 0, len(o.PortList))
for _, p := range o.PortList {
ports = append(ports, corev1.ServicePort{
Name: strings.ToLower(p.Name),
Expand Down
2 changes: 1 addition & 1 deletion istioctl/cmd/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ istioctl analyze -L
resource.Namespace(selectedNamespace), resource.Namespace(istioNamespace), nil, true, analysisTimeout)

// Check for suppressions and add them to our SourceAnalyzer
var suppressions []snapshotter.AnalysisSuppression
suppressions := make([]snapshotter.AnalysisSuppression, 0, len(suppress))
for _, s := range suppress {
parts := strings.Split(s, "=")
if len(parts) != 2 {
Expand Down
2 changes: 1 addition & 1 deletion istioctl/cmd/convert_ingress.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func convertConfigs(readers []io.Reader, writer io.Writer, client kubernetes.Int
}

func readConfigs(readers []io.Reader) ([]model.Config, []*v1beta1.Ingress, error) {
out := make([]model.Config, 0)
out := make([]model.Config, 0, len(readers))
outIngresses := make([]*v1beta1.Ingress, 0)

for _, reader := range readers {
Expand Down
6 changes: 3 additions & 3 deletions istioctl/cmd/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ THIS COMMAND IS STILL UNDER ACTIVE DEVELOPMENT AND NOT READY FOR PRODUCTION USE.
return err
}

matchingServices := []v1.Service{}
matchingServices := make([]v1.Service, 0, len(svcs.Items))
for _, svc := range svcs.Items {
if len(svc.Spec.Selector) > 0 {
svcSelector := k8s_labels.SelectorFromSet(svc.Spec.Selector)
Expand Down Expand Up @@ -220,8 +220,8 @@ func extendFQDN(host string) string {

// getDestRuleSubsets gets names of subsets that match any pod labels (also, ones that don't match).
func getDestRuleSubsets(subsets []*v1alpha3.Subset, podsLabels []k8s_labels.Set) ([]string, []string) {
matchingSubsets := []string{}
nonmatchingSubsets := []string{}
matchingSubsets := make([]string, 0, len(subsets))
nonmatchingSubsets := make([]string, 0, len(subsets))
for _, subset := range subsets {
subsetSelector := k8s_labels.SelectorFromSet(subset.Labels)
if matchesAnyPod(subsetSelector, podsLabels) {
Expand Down
2 changes: 1 addition & 1 deletion istioctl/pkg/writer/envoy/configdump/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func (c *ConfigWriter) PrintClusterDump(filter ClusterFilter) error {
if err != nil {
return err
}
filteredClusters := protio.MessageSlice{}
filteredClusters := make(protio.MessageSlice, 0, len(clusters))
for _, cluster := range clusters {
if filter.Verify(cluster) {
filteredClusters = append(filteredClusters, cluster)
Expand Down
9 changes: 5 additions & 4 deletions istioctl/pkg/writer/envoy/configdump/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func (c *ConfigWriter) PrintListenerSummary(filter ListenerFilter) error {
return err
}

verifiedListeners := []*listener.Listener{}
verifiedListeners := make([]*listener.Listener, 0, len(listeners))
for _, l := range listeners {
if filter.Verify(l) {
verifiedListeners = append(verifiedListeners, l)
Expand Down Expand Up @@ -179,8 +179,9 @@ var (
)

func retrieveListenerMatches(l *listener.Listener) []filterchain {
resp := []filterchain{}
for _, filterChain := range l.GetFilterChains() {
fChains := l.GetFilterChains()
resp := make([]filterchain, 0, len(fChains))
for _, filterChain := range fChains {
match := filterChain.FilterChainMatch
if match == nil {
match = &listener.FilterChainMatch{}
Expand Down Expand Up @@ -323,7 +324,7 @@ func describeDomains(vh *route.VirtualHost) string {
}

func describeRoutes(vh *route.VirtualHost) string {
routes := []string{}
routes := make([]string, 0, len(vh.GetRoutes()))
for _, route := range vh.GetRoutes() {
routes = append(routes, describeMatch(route.GetMatch()))
}
Expand Down
2 changes: 1 addition & 1 deletion istioctl/pkg/writer/envoy/configdump/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (c *ConfigWriter) PrintRouteDump(filter RouteFilter) error {
if err != nil {
return err
}
filteredRoutes := protio.MessageSlice{}
filteredRoutes := make(protio.MessageSlice, 0, len(routes))
for _, route := range routes {
if filter.Verify(route) {
filteredRoutes = append(filteredRoutes, route)
Expand Down
2 changes: 1 addition & 1 deletion istioctl/pkg/writer/pilot/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (s *StatusWriter) PrintSingle(statuses map[string][]byte, proxyName string)
func (s *StatusWriter) setupStatusPrint(statuses map[string][]byte) (*tabwriter.Writer, []*writerStatus, error) {
w := new(tabwriter.Writer).Init(s.Writer, 0, 8, 5, ' ', 0)
_, _ = fmt.Fprintln(w, "NAME\tCDS\tLDS\tEDS\tRDS\tISTIOD\tVERSION")
var fullStatus []*writerStatus
fullStatus := make([]*writerStatus, 0, len(statuses))
for pilot, status := range statuses {
var ss []*writerStatus
err := json.Unmarshal(status, &ss)
Expand Down
4 changes: 2 additions & 2 deletions operator/pkg/util/progress/progress.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ const inProgress = `{{ yellow (cycle . "-" "-" "-" " ") }} `
// createStatus will return a string to report the current status.
// ex: - Processing resources for components. Waiting for foo, bar
func (p *Log) createStatus(maxWidth int) string {
comps := []string{}
wait := []string{}
comps := make([]string, 0, len(p.components))
wait := make([]string, 0, len(p.components))
for c, l := range p.components {
comps = append(comps, name.UserFacingComponentName(name.ComponentName(c)))
wait = append(wait, l.waiting...)
Expand Down
6 changes: 3 additions & 3 deletions pilot/pkg/model/push_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -1555,7 +1555,7 @@ func (ps *PushContext) initMeshNetworks() {
}

registryNames := getNetworkRegistries(networkConf)
gateways := []*Gateway{}
gateways := make([]*Gateway, 0, len(gws))

for _, gw := range gws {
gateways = append(gateways, getGatewayAddresses(gw, registryNames, ps.ServiceDiscovery)...)
Expand All @@ -1571,7 +1571,7 @@ func (ps *PushContext) initMeshNetworks() {
func (ps *PushContext) initClusterLocalHosts(e *Environment) {
// Create the default list of cluster-local hosts.
domainSuffix := e.GetDomainSuffix()
defaultClusterLocalHosts := make([]host.Name, 0, len(defaultClusterLocalNamespaces))
defaultClusterLocalHosts := make([]host.Name, 0)
for _, n := range defaultClusterLocalNamespaces {
defaultClusterLocalHosts = append(defaultClusterLocalHosts, host.Name("*."+n+".svc."+domainSuffix))
}
Expand Down Expand Up @@ -1617,7 +1617,7 @@ func (ps *PushContext) initClusterLocalHosts(e *Environment) {
}

func getNetworkRegistries(network *meshconfig.Network) []string {
var registryNames []string
registryNames := make([]string, 0, len(network.Endpoints))
for _, eps := range network.Endpoints {
if eps != nil && len(eps.GetFromRegistry()) > 0 {
registryNames = append(registryNames, eps.GetFromRegistry())
Expand Down
4 changes: 2 additions & 2 deletions pilot/pkg/serviceregistry/aggregate/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ func (c *Controller) GetIstioServiceAccounts(svc *model.Service, ports []int) []
out[sa] = struct{}{}
}
}
result := []string{}
result := make([]string, 0, len(out))
for k := range out {
result = append(result, k)
}
Expand All @@ -385,7 +385,7 @@ func (c *Controller) GetIstioServiceAccounts(svc *model.Service, ports []int) []
}
}
expanded := spiffe.ExpandWithTrustDomains(result, tds)
result = []string{}
result = make([]string, 0, len(expanded))
for k := range expanded {
result = append(result, k)
}
Expand Down
2 changes: 1 addition & 1 deletion pilot/pkg/xds/ads.go
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ func (s *DiscoveryServer) startPush(req *model.PushRequest) {
s.adsClientsMutex.RLock()

// Create a temp map to avoid locking the add/remove
pending := []*Connection{}
pending := make([]*Connection, 0, len(s.adsClients))
for _, v := range s.adsClients {
pending = append(pending, v)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/adsc/adsc.go
Original file line number Diff line number Diff line change
Expand Up @@ -719,7 +719,7 @@ func (a *ADSC) Save(base string) error {

func (a *ADSC) handleCDS(ll []*cluster.Cluster) {

cn := []string{}
cn := make([]string, 0, len(ll))
cdsSize := 0
edscds := map[string]*cluster.Cluster{}
cds := map[string]*cluster.Cluster{}
Expand Down
2 changes: 1 addition & 1 deletion tools/istio-iptables/pkg/cmd/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ package cmd
import "strings"

func FormatIptablesCommands(commands [][]string) []string {
output := make([]string, 0)
output := make([]string, 0, len(commands))
for _, cmd := range commands {
output = append(output, strings.Join(cmd, " "))
}
Expand Down

0 comments on commit 8dfaf33

Please sign in to comment.