Five letters problem: Python vs C++ vs C#

The task is to find groups of 5 English words in which each letter appears at most once, i.e. 25 letters total. These must be “real” English words from the dictionary, e.g. fjord gucks nymph vibex waltz. I chose an algorithm and wrote an implementation in C++, Python and C#:
https://github.com/ikriv-samples/FiveLetters.

This may be not the most optimal algorithm, but this post about comparison of the languages.

  • C++ is fast (30s), but verbose. Working with dictionaries is hell.
  • Python is slow (600s), but easy to write. The lack of types bites you later.
  • C# is in the middle (100s). OK to write. Strong typing without typedefs is pain. Literals are a major pain.

The algorithm I chose may not be the fastest, but the important point it’s the same in all 3 languages. The program is single threaded. Paralellizing may be the easiest in C# with parallel foreach, but I haven’t tried it yet.

C++: great performance, but verbose, and working with dictionaries and iterators is painful. Surprisingly, memory management was not a big deal, with vectors and other goodies, it’s relatively straightforward.

Python: a pleasure to write, but when you come back to the project 4 months later, trying to remember that this thing is a map from integer to a list of integer pais is kind of hard. Yes, Python has type annotations, but then they make it almost as verbose as C# (Dict[int,List[Tuple[int,int]]] is no fun), you’d need to import all this stuff from typing, and still the support for type correctness is an afterthought.

C#: lack of proper typedefs is painful. using Type=stuff alleviates it somewhat, but it has quirks: see this StackOverflow question. Literals for structured data are a big pain. What in Python looks like [{ 0 : [(0,0)] }], and even in C++ loosk liek { 0,{{0,0}} }, translates to C# as

new List { new MaskToPairMap { { 0, new List { (0, 0) } } } }.

I remember writing special functions for making literals like this shorter and readable.
The good things going for C# are LINQ and nice lambdas, but I did not have much use for them in this particular case.

Leave a Reply

Your email address will not be published. Required fields are marked *