Blog

  • Complex password validation regular expression

    I needed a regular expression to validate the following

    • 12 characters
    • 1 number
    • 1 special character

    To check for a ‘special character’, my first attempt created an extremely long regex with all the various possible characters. This become unmanagable so I decided to opt for ranges of ASCII characters. The resulting regex is

    ^(?=.*?([A-Z]|[a-z]))(?=.*?[0-9])(?=.*?([\x20-\x2F]|[\x3A-\x40]|[\x5B-\x60]|[\x7B-\xFF])).{12,}$

    When we break this down, the first group looks for a letter character, the second looks for a number and the third looks for our special characters. Obviously then we ensure a minimum length of 12 characters.

  • Should we always use StringBuilder in C#

    I’ve seen developers use StringBuilder to concatenate 2 small strings in C# and I started thinking, are we so used to reaching for StringBuilder that we never stop and think, is this overkill? So I wanted to run some benchmarks and find the sweat spot in terms of speed and memory allocation where it makes sense to use StringBuilder instead of simple concatenation.

    Lets start off with a very simple example.

    Now ofcourse this is only doing one string operation by combining the 4 individual strings in one go, but it is some I see some developers doing. How does it fair in terms of bench marking.

    The simple string concatenations is almost twice as fast and 1/3 the memory alloction.

    Lets ramp it up so the simple concatenation is actually doing 4 operations.

    Here we can see StringBuilder beings to outperform simple concatenation in terms of pure speed, but slightly higher memory allocation.

    What happens if we make are strings much larger?

    Interestingly StringBuilder is slower in this example and still has higher memory allocation.

    What happens if we double our 4 small string concatenation operations to 8?

    Here we are begining to see what we would expected, StringBuilder is out performing simple concatenation in terms of speed and memory allocation.

    Lets check again with 12 string operations.

    Again StringBuilder is outperforming simple concatenation.

    Lets take it up to 100 concatenations

    Here we really start to see the benefit of StringBuilder.

    Summary

    In my testing, StringBuilder didn’t really pay off until concatenating> 6 strings.

  • Hello world!

    Welcome to WordPress. This is your first post. Edit or delete it, then start writing!