sancarn / stdVBA

VBA Standard Library - A Collection of libraries to form a common standard layer for modern VBA applications.
MIT License
294 stars 58 forks source link

StringBuilder performance tweaks #72

Closed sihlfall closed 1 year ago

sihlfall commented 1 year ago

This is a great project! These classes save a lot of work.

Maybe my tweaking of StringBuilder is of interest to someone.

The StringBuilder class relies on string concatenation (repeated &), which results in a lot of string creation and copying. This can be overcome by using an exponentially growing buffer. Since I needed such a StringBuilder, I created one (https://github.com/sihlfall/vba-stringbuilder/).

I have been able to apply the ideas used there to stdVBA's StringBuilder class. In addition, I have modified StringBuilder to create the variable substitution dictionary lazily (so it is only created when it is actually used).

The modified class can be found here:

https://github.com/sihlfall/vba-stringbuilder/blob/master/comparison/stdvba-ssb/stdStringBuilderSsb.cls

It should, after renaming, be a drop-in replacement for the existing class.

Performance improvements are considerable. For instance, consider appending n single-character strings to an initial string of length 20,000:

Initial string size: 20,000
   n             stdStringBuilder     stdStringBuilderSsb (= modified version)
 100                 0.86ms                     0.01ms
 200                 1.41ms                     0.02ms
 400                 2.52ms                     0.03ms
 800                 5.84ms                     0.06ms
1600                10.82ms                     0.12ms

For a larger initial string:

Initial string size: 200,000
   n             stdStringBuilder     stdStringBuilderSsb (= modified version)
 100                13.72ms                     0.20ms
 200                26.84ms                     0.21ms
 400                51.00ms                     0.22ms
 800               104.26ms                     0.25ms
1600               206.13ms                     0.30ms
sancarn commented 1 year ago

Thanks a bunch, if you create a PR i'd be happy to apply it :) Else I could update it myself later 👍 Great work!

FlameHorizon commented 1 year ago

@sihlfall can you post your benchmark code here? I would like to take bite at it as well. Thanks.

sihlfall commented 1 year ago

@FlameHorizon See here:

https://github.com/sihlfall/vba-stringbuilder/tree/master/timing

sancarn commented 1 year ago

Closed by #73