Search code examples
c++optimizationlanguage-agnostic

What is pessimization?


There is a comment on the question Can the use of C++11's auto improve performance? that scored many votes and suggests “makes it less likely to unintentionally pessimize” as an answer. I've never noticed this term before. I guess it is somehow the opposite of optimization.

Can anyone give a more detailed definition? What does it mean in the context of programming? How would pessimized code look like?


Solution

  • It's mostly a play on words, a pessimist is the opposite of an optimist. And pessimisation is writing less than optimal code.

    Both compilers and the programmer can pessimise code by having bad constructs that for example copy things when it isn't required. The auto keyword will at the very least ensure that you get the "closest type", so there is no (unnecessary) type conversion.

    Note that pessimisation is when there is no BENEFIT to the code being "not optimal":

    It is not pessimisation "if we spent six months optimising this, it would run 0.5% faster". Unless it's a requirement to be 0.5% faster, spending six months on it is probably a waste of time.

    Also, required functionality, such as security, is not pessimisation: "The code is slower than it possibly could be because we made it secure".

    A debug build is mot "pessimal" because it has asserts to catch NULL pointer dereferences and checking the index of array accesses, etc. As long as those asserts and checks are written such that they "disappear" when you enable the release mode. [and if your code is running a nuclear power-plant, you probably don't want crashes EVER, see "security" above]

    An old example I've seen is this C-string loop:

    char str [large_number] = "... several kilobytes of text (read from file) ... ";
    
    for(char *p = str; p < str+strlen(str); p++)
    {
       ... do stuff with p ... 
    }
    

    If do stuff with p is sufficiently complex, the compiler won't realize that strlen is a constant value, and will perform strlen every iteration of the loop. The loop will run MUCH faster if we did:

    for(char *p = str, *e = str+strlen(str); p < e; p++)
    {
       ... do stuff with p ... 
    }
    

    [Not an example of auto, I'm afraid]