Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: avoid unnecessary deep copy #628

Closed

Conversation

crenshaw-dev
Copy link
Member

I'm not convinced we need to deep copy these objects at all. But to be cautious, I think we can save some resources by only deep copying if we need to mutate the objects.

Here's the benchmark result:

before: Benchmark_threeWayMergePatch-16            23341             52004 ns/op           39070 B/op        810 allocs/op
after:  Benchmark_threeWayMergePatch-16            24838             48706 ns/op           37709 B/op        800 allocs/op

We save a little memory and CPU.

Here's the benchmark code:

func Benchmark_threeWayMergePatch(b *testing.B) {
	orig := []byte(`
apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: default
`)
	config := []byte(`
apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: default
`)
	live := []byte(`
apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: default
`)

	origUnstructured := unstructured.Unstructured{}
	err := yaml.Unmarshal(orig, &origUnstructured)
	require.NoError(b, err)
	configUnstructured := unstructured.Unstructured{}
	err = yaml.Unmarshal(config, &configUnstructured)
	require.NoError(b, err)
	liveUnstructured := unstructured.Unstructured{}
	err = yaml.Unmarshal(live, &liveUnstructured)
	require.NoError(b, err)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_, err := ThreeWayDiff(&origUnstructured, &configUnstructured, &liveUnstructured)
		require.NoError(b, err)
	}
}

Signed-off-by: Michael Crenshaw <350466+crenshaw-dev@users.noreply.github.com>
Copy link

sonarcloud bot commented Sep 16, 2024

@crenshaw-dev
Copy link
Member Author

Fixing the test failure makes the change more costly than the original. Leaving it as-is for now.

@crenshaw-dev crenshaw-dev deleted the avoid-unnecessary-deepcopy branch September 16, 2024 10:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant