Skip to content

Optimize DafnySequence<Character> to String#819

Closed
olivergillespie wants to merge 2 commits intosmithy-lang:main-1.xfrom
olivergillespie:reduce-to-string-allocs
Closed

Optimize DafnySequence<Character> to String#819
olivergillespie wants to merge 2 commits intosmithy-lang:main-1.xfrom
olivergillespie:reduce-to-string-allocs

Conversation

@olivergillespie
Copy link
Contributor

Optimize performance of ToNative$Simple.String. I saw in an allocation profile of my application that this code is creating a lot of garbage, principally from calling Character.toString on every element, which creates a whole String object and backing byte[]. The Stream is wasteful too.

Move to a StringBuilder and for loop. A very rough benchmark shows about 80% reduction in allocations and total time taken.

Small string (4 chars):

Time Allocation
Baseline 159 ns/op 608 bytes/op
Optimized 37 ns/op 96 bytes/op

Larger string (88 chars):

Time Allocation
Baseline 2079 ns/op 5360 bytes/op
Optimized 419 ns/op 816 bytes/op

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@olivergillespie olivergillespie requested a review from a team as a code owner October 9, 2025 12:54
texastony pushed a commit that referenced this pull request Oct 9, 2025
(Re-cutting #819 on
[olivergillespie](https://github.com/olivergillespie)'s behalf)

Optimize performance of `ToNative$Simple.String`. I saw in an allocation
profile of my application that this code is creating a lot of garbage,
principally from calling `Character.toString` on every element, which
creates a whole `String` object and backing `byte[]`. The `Stream` is
wasteful too.

Move to a `StringBuilder` and for loop. A very rough benchmark shows
about 80% reduction in allocations and total time taken.

Small string (4 chars):
| | Time | Allocation |
|---------|------|-------|
| Baseline | 159 ns/op | 608 bytes/op |
| Optimized | 37 ns/op | 96 bytes/op |

Larger string (88 chars):
| | Time | Allocation |
|---------|------|-------|
| Baseline | 2079 ns/op | 5360 bytes/op |
| Optimized | 419 ns/op | 816 bytes/op |


By submitting this pull request, I confirm that you can use, modify,
copy, and redistribute this contribution, under the terms of your
choice.

---------

Co-authored-by: Oli Gillespie <ogillesp@amazon.com>
@olivergillespie
Copy link
Contributor Author

Merged in #820, thanks!

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