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

types/basetypes: Reduce memory allocations of (ObjectValue).ToTerraformValue() #791

Merged
merged 2 commits into from
Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/unreleased/BUG FIXES-20230703-123518.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
kind: BUG FIXES
body: 'types/basetypes: Minor reduction of memory allocations for `ObjectValue` type
`ToTerraformValue()` method, which decreases provider operation durations at scale'
time: 2023-07-03T12:35:18.484275-04:00
custom:
Issue: "775"
6 changes: 4 additions & 2 deletions types/basetypes/object_value.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,10 +262,12 @@ func (o ObjectValue) Type(ctx context.Context) attr.Type {
// ToTerraformValue returns the data contained in the attr.Value as
// a tftypes.Value.
func (o ObjectValue) ToTerraformValue(ctx context.Context) (tftypes.Value, error) {
attrTypes := map[string]tftypes.Type{}
for attr, typ := range o.AttributeTypes(ctx) {
attrTypes := make(map[string]tftypes.Type, len(o.attributeTypes))

for attr, typ := range o.attributeTypes {
attrTypes[attr] = typ.TerraformType(ctx)
}

objectType := tftypes.Object{AttributeTypes: attrTypes}

switch o.state {
Expand Down
30 changes: 30 additions & 0 deletions types/basetypes/object_value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package basetypes
import (
"context"
"math/big"
"strconv"
"testing"

"github.com/google/go-cmp/cmp"
Expand All @@ -15,6 +16,35 @@ import (
"github.com/hashicorp/terraform-plugin-go/tftypes"
)

func BenchmarkObjectValueToTerraformValue1000(b *testing.B) {
benchmarkObjectValueToTerraformValue(b, 1000)
}

func benchmarkObjectValueToTerraformValue(b *testing.B, attributes int) {
attributeTypes := make(map[string]attr.Type, attributes)
attributeValues := make(map[string]attr.Value, attributes)
ctx := context.Background()

for i := 0; i < attributes; i++ {
attributeName := "testattr" + strconv.Itoa(i)
attributeTypes[attributeName] = BoolType{}
attributeValues[attributeName] = NewBoolNull()
}

value := NewObjectValueMust(
attributeTypes,
attributeValues,
)

for n := 0; n < b.N; n++ {
_, err := value.ToTerraformValue(ctx)

if err != nil {
b.Fatalf("unexpected ToTerraformValue error: %s", err)
}
}
}

func TestNewObjectValue(t *testing.T) {
t.Parallel()

Expand Down