DEV Community

Cover image for Benchmark Strings
burak
burak

Posted on

Benchmark Strings

How much do you know string?

Since when I started day developing code, generally use the string data type. They always ask questions about strings in every job interview. Especially the first times. Today I'll talk about how much do you know strings?

Microsoft says: a string is an object of type String whole value is text. πŸ‘‰ Microsoft

Microsoft says: the string keyword is an alias for System.String; πŸ‘‰ Microsoft

Let's declare and initialize strings

// Declare without initializing.
string username;

// Initialize to null.
string username = null;

// Initialize as an empty string.
string username = System.String.Empty;

// Initialize as an empty string with ""
string username = "";

// Initialize with a regular string literal.
string oldPath = "c:\\documents";

// Initialize with a verbatim string literal.
string newPath = @"c:\documents;

// Use System.String if you prefer.
System.String email = "burakseyhan8@gmail.com";

//string concanate
var title = "Hi";
var body = "Thank" + "you";
body = $"{body} for read";

MessageBox.Show("body");
Enter fullscreen mode Exit fullscreen mode

If I need text data I have to use String. Or I got the current date if I wanna store the current date in the database I'll use ToString().

Strings objects are immutable: Strings are can not be changed after they have been created. So let's write basic code.

string firstName = "burak";
string lastName = "seyhan";

firstName += lastName;

Console.WriteLine(firstName);
Enter fullscreen mode Exit fullscreen mode

Escape Sequence Characters

Benchmark

Player 1 : + operator
Player 2 : String.Concat()
Player 3 : StringBuilder

  • + operator :

Concatenate using with + operator. With + operator create a new string.

text = "Burak" + i.ToString();

  • String.Concat() :

String.Concat() function also allows to concatenate strings. You can pass all strings as function parameters.

  • StringBuilder :

StringBuilder is a class that is useful to represent a mutable string of characters and it is an object of System.Text namespace. Strings are immutable and StringBuilder is mutable. Mutable means once an instance of the class is created, then the same instance will be used to perform any operations. Although the StringBuilder is a dynamic object that allows you to expand the number of characters in the string that it encapsulates, you can specify a value for the maximum number of characters that it can hold. This value is called the capacity of the StringBuilder object.

Method and Definitions:

  • StringBuilder.Append: This method will append the given string value to the end of the current StringBuilder.

  • StringBuilder.AppendFormat: It will replace a format specifier passed in a string with formatted text.

  • StringBuilder.Insert: It inserts a string at the specified index of the current StringBuilder.

  • StringBuilder.Remove: It removes a specified number of characters from the current StringBuilder.

  • StringBuilder.Replace: It replaces a specified character at a specified index.

StringBuilder and String.Concat differs in one critical point. When the String.Concat function is used, all strings to concatenate must be given as parameters. By using the StringBuilder class, these values ​​can be added step by step by calling the add function.

Here is the rule. I create 3 players. Every player has their own specific role. Here is the rule. I create 3 players. Every player has their own specific role. Every player iterates 100000 times then all player's results writes on the screen.

Let's write some code here πŸ‘¨πŸ»β€πŸ’»

using System;
using System.Diagnostics;
using System.Text;

namespace StringvsStringBuilder
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var count = 100000;
            string text = string.Empty;

            var stopWatch = Stopwatch.StartNew();

            /*
            Console.WriteLine("+ operator");
            for (int i = 0; i <= count; i++)
            {
                text = "burak " + string.Empty + i.ToString();
                Console.WriteLine(text);
            }

            Console.WriteLine($"Content: {text} Execution Time Of : {stopWatch.Elapsed.TotalMilliseconds}");
            stopWatch.Stop();
            Console.WriteLine("*********************");
            */

            /*
            Console.WriteLine("String.Concat");

            for (int i = 0; i <= count; i++)
            {
                String.Concat("burak", string.Empty, "seyhan", i.ToString());
            }
            stopWatch.Stop();
            Console.WriteLine($"Content: {text} Execution Time Of : {stopWatch.Elapsed.TotalMilliseconds}");
            Console.WriteLine("*********************");
            */


            Console.WriteLine("String Builder");
            var builder = new StringBuilder();
            for (int i = 0; i <= count; i++)
            {
                builder.Append("burak");
                builder.Append("");
                builder.AppendLine("seyhan");
                builder.AppendLine(i.ToString());
            }

            stopWatch.Stop();
            Console.WriteLine($"Content: {text} Execution Time Of : {stopWatch.Elapsed.TotalMilliseconds}");
            Console.WriteLine("*********************");


            Console.ReadKey();
            Console.WriteLine("Program finished");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Results:

    • operator Content: burak 100000 Execution Time Of: 3307.8574
  1. String Concat
    Content: Execution Time Of: 222.8163

  2. string builder
    Content: Execution Time Of: 178.1494

πŸ₯‡ 🍾 is string builder πŸ‘πŸ» πŸ‘πŸ» πŸ‘πŸ»

Thank you for reading πŸ§‘πŸ»β€πŸ’»

Top comments (0)