Thread: Do C compliers make "frequently called function" an inline function automatically?

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    6

    Arrow Do C compliers make "frequently called function" an inline function automatically?

    So the question is -


    Code:
    //will this code runs slower-
    for (int i = 0; i < strlen(str); i++)
    {......}
    
    //compare to this-
    
    int length = strlen(str);
    for (int i = 0; i < length; i++)
    {.......}
    Or our "MODERN & SMART" compliers will automatically make strlen() inline as it is inside loop?

    I think this is the case with c++ compilers,isnt it ?

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Why not put your code to the test, in your compiler? Enter a nice long string, and time it with clock()?

    That's one of the best things about programming a computer, imo. You can test your idea's, ON YOUR SYSTEM, and with your own compiler, and answer the question authoritatively, in many cases.

    I'm a big fan of using the second version. Why rely on the compiler to do simple things?

  3. #3
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Or you could compile and check the assembly output to compare.

  4. #4
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by mannu1200 View Post

    Or our "MODERN & SMART" compliers will automatically make strlen() inline as it is inside loop?

    I think this is the case with c++ compilers,isnt it ?
    Look again at the code. The issue isn't whether a function is being inlined. You probably want to avoid continually recalculating the result of strlen over and over, right? Even if it's inlined, this work is not a constant-time operation. I don't see any way a compiler could automatically know that strlen(...) called with a particular address should always gives the same result in this context. Therefore, your idea of caching the result in length is probably the best way to ensure that this work is only done once.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-27-2008, 11:44 PM
  2. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  3. Replies: 6
    Last Post: 05-18-2003, 06:29 PM
  4. Write and read the book called "registry""
    By CodeMonkey in forum Windows Programming
    Replies: 4
    Last Post: 03-10-2002, 10:45 AM
  5. Replies: 1
    Last Post: 12-13-2001, 12:09 AM

Tags for this Thread