Skip to main content

C# execution vs Python execution (performance)

So few days ago I wrote about how python is slower than C#.

So I created simple script for python using strings and dictionaries:

from datetime import datetime
import random
dic = {}
letter = 'qwertyuiopasdfghjklz'
for i in range(10000001):
    if i%1000000==0:
        now = datetime.now()
        print(str(now))
    
    s = ""
    for j in range(50):
        s += letter[random.randrange(20)]
    if s not in dic:
        dic[s] = True


And same thing in C#:

using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, bool> dic = new Dictionary<string, bool>();
            Random r = new Random();
            string letter = "qwertyuiopasdfghjklz";
            for (int i=0;i<10000001;i++)
            {
                if (i % 1000000 == 0)
                {
                    Console.WriteLine(DateTime.Now.ToString());
                }
                string s = "";
                for(int j=0;j<50;j++)
                {
                    s += letter[r.Next(20)];
                }
                if(!dic.ContainsKey(s))
                {
                    dic.Add(s, true);
                }
            }
        }
    }
}


Here is execution time for Python:

pepe@pepe-Alienware-13-R3:~/code$ python3 sp.py 

2020-07-09 14:54:45.577254

2020-07-09 14:55:10.225260

2020-07-09 14:55:35.141779

2020-07-09 14:56:00.896873


Here is execution for C#:

Debug

7/9/2020 10:01:19 PM

7/9/2020 10:01:22 PM

7/9/2020 10:01:25 PM

7/9/2020 10:01:28 PM

Release

7/9/2020 10:02:20 PM

7/9/2020 10:02:23 PM

7/9/2020 10:02:25 PM

7/9/2020 10:02:28 PM

Times between 2-3 seconds for C# vs around 25 seconds for Python. Difference is quite huge. Now consider you are experimenting with ideas and if you use Python, you have to wait 8 times longer. In case your experimentation takes 1 day in C# vs 8 days in python, you will naturally want to go for one day...