What is pessimization?

前端 未结 3 776
甜味超标
甜味超标 2021-02-20 01:30

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 a

3条回答
  •  悲哀的现实
    2021-02-20 02:04

    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]

提交回复
热议问题