Quest for speed: String compares



  • THE POST BELOW IS MORE THAN 5 YEARS OLD. RELATED SUPPORT INFORMATION MIGHT BE OUTDATED OR DEPRECATED

    On 18/09/2004 at 11:58, xxxxxxxx wrote:

    User Information:
    Cinema 4D Version:   8.503 
    Platform:   Windows  ;   
    Language(s) :     C++  ;

    ---------
    In a never-ending quest to increase execution speed of my plugin (which has a lot to do), I was considering the effect of statements like the following (pseudo-code) :

      
    String token;  
    while (condition)  
    {  
    if (!(token = GetToken())) throw Error;  
    if (token == "test1") do something;  
    else if (token == "test2") do something 2;  
    // and so on  
    }  
    

    So, the question is this: Does the code create a const String() of the 'test' compare strings each time the loop is done or is the compiler smart enough to have this done once? Since these loops can be repeated tens, hundreds, or more times, I was considering the following:

      
    const String test1Str = String("test1");  
    const String test2Str = String("test2");  
    // and so on  
    String token;  
    while (condition)  
    {  
    if (!(token = GetToken())) throw Error;  
    if (token == test1Str) do something;  
    else if (token == test2Str) do something 2;  
    // and so on  
    }  
    

    The overhead of creating all of the constant Strings should be mitigated by the number of times each compare is done within the loop.

    Final question: Do you see any advantage to the method 2 over method 1?

    Thanks,
    Robert



  • THE POST BELOW IS MORE THAN 5 YEARS OLD. RELATED SUPPORT INFORMATION MIGHT BE OUTDATED OR DEPRECATED

    On 18/09/2004 at 12:47, xxxxxxxx wrote:

    Quote: So, the question is this: Does the code create a const String() of the 'test' compare strings each time the loop is done or is the compiler smart enough to have this done once?
    >
    > * * *
    >
    > * * *

    _


    Afaik it is not smart enough. It has to initialize the String by calling the constructor. It has to do this everytime when initializing (and the constructor then must check its arguments for validity).

    I would say this costs valuable time, especially when dealing with recursive functions. I would surely prefer the second method therefore.

    But only performance tests can really solve this (cause theory is sometimes different as you might know :)



  • THE POST BELOW IS MORE THAN 5 YEARS OLD. RELATED SUPPORT INFORMATION MIGHT BE OUTDATED OR DEPRECATED

    On 18/09/2004 at 14:16, xxxxxxxx wrote:

    This was my thinking also; it would see the constant text, construct a String(), then call the String '==' operator for each encounter.

    I'm going to go with the second method and see how it differs in time.

    Thanks Katachi!


Log in to reply