C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This program is a simple benchmark framework that compares how similar data is appended.
C# program that tests data types
using System;
using System.Diagnostics;
using System.Text;
class Program
{
static void Main()
{
const int m = 100000;
// Char versus Int
Stopwatch s1 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
StringBuilder s = new StringBuilder(1000);
for (int v = 0; v < 1000; v++)
{
s.Append(1);
}
}
s1.Stop();
Stopwatch s2 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
StringBuilder s = new StringBuilder(1000);
for (int v = 0; v < 1000; v++)
{
s.Append('1');
}
}
s2.Stop();
// Bool versus string
Stopwatch s3 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
StringBuilder s = new StringBuilder(4000);
for (int v = 0; v < 1000; v++)
{
s.Append(true);
}
}
s3.Stop();
Stopwatch s4 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
StringBuilder s = new StringBuilder(4000);
for (int v = 0; v < 1000; v++)
{
s.Append("True");
}
}
s4.Stop();
// Char versus string
Stopwatch s5 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
StringBuilder s = new StringBuilder(1000);
for (int v = 0; v < 1000; v++)
{
s.Append('a');
}
}
s5.Stop();
Stopwatch s6 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
StringBuilder s = new StringBuilder(1000);
for (int v = 0; v < 1000; v++)
{
s.Append("a");
}
}
s6.Stop();
Console.WriteLine("{0},{1},{2},{3},{4},{5}",
s1.ElapsedMilliseconds, s2.ElapsedMilliseconds,
s3.ElapsedMilliseconds, s4.ElapsedMilliseconds,
s5.ElapsedMilliseconds, s6.ElapsedMilliseconds);
}
}
And: The third pair tests a char against its same text in string format. It uses a one-character string.
Note: In this benchmark you can only fairly compare the three pairs against their other halves.
Results: Appending a char is faster than appending an int. A string was faster than a bool. And a char was faster than a string.
StringBuilder parameter types test:
Append int: 12677 ms
Append char: 1328 ms [faster]
Append bool: 2268 ms
Append string 1: 2095 ms [faster]
Append char: 1344 ms [faster]
Append string 2: 1904 ms