How to write a better strlen function?

后端 未结 7 1957
Happy的楠姐
Happy的楠姐 2020-12-30 06:43

I am reading \"Write Great Code Volume 2\" and it shows the following strlen impelementation:

int myStrlen( char *s )
{
    char *start;
    start = s;
    w         


        
7条回答
  •  情深已故
    2020-12-30 07:14

    As others have pointed out, a faster algorithm reads entire words instead of individual characters and uses bitwise operations to find the terminating null. Be mindful of word-aligning your pointer if you take this approach, as some CPU architectures won't let you read words from an unaligned address (and it's a great way to trigger a segfault even on architectures that don't require alignment).

    Bottom line:

    Great code emphasizes readability over speed in all but the most performance-critical cases. Write your code as clearly as you can and only optimize the parts that prove to be bottlenecks.

提交回复
热议问题