Meska
Meska

Reputation: 85

Parallelism takes much more time than a regular foreach

i wanted to improve my caesar cypher by adding parallelism capabilities but further measurement of code has demonstrated that the parallelism approach takes more time to finish than the normal approach.

why?

normal

public string CaesarEncrypt(string text, int positions, char[] charSet = null) {

    if (string.IsNullOrEmpty(charSet)) {
        charSet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789").ToCharArray();
    }

    List<char> charList = charSet.ToList();
    StringBuilder sb = new StringBuilder { Capacity = text.Length };

    foreach (char c in text) {
        int charPos = charList.IndexOf(c);

        if ((charPos == -1)) {
            sb.Append(c);
        } else {
            while (!(((charPos + positions) < (charSet.Length)))) {
                charPos -= charSet.Length;
            }
            sb.Append(charSet(charPos + positions));
        }
    }
    return sb.ToString();
}

parallel

public string CaesarEncrypt(string text, int positions, char[] charSet = null) {

    if (string.IsNullOrEmpty(charSet)) {
        charSet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789").ToCharArray();
    }

    List<char> charList = charSet.ToList();
    StringBuilder sb = new StringBuilder { Capacity = text.Length };

    Parallel.ForEach(text.ToArray(), (char c) =>
    {
        int charPos = charList.IndexOf(c);

        if ((charPos == -1)) {
            sb.Append(c);

        } else {
            while (!(((charPos + positions) < (charSet.Length)))) {
                charPos -= charSet.Length;
            }
            sb.Append(charSet(charPos + positions));

        }
    });
    return sb.ToString();
}

Upvotes: 0

Views: 84

Answers (1)

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18013

The management of the multi-threading has some cost. If the task in the body of the cycle is too tiny, this overhead can be larger than the gain of the multi-threading.

The other problem here that you append a StringBuilder inside if the parallel body. Since it is not guaranteed in which order the threads will finish, you might get a chaotic result at the end.

Upvotes: 3

Related Questions