How to write a better strlen function?

后端 未结 7 1953
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:37

    Reading a variable that is not of the same size as the machine data bus size is expensive, because the machine can only read variables of that size. Therefore, whenever something of different size (let's say smaller) is requested, the machine must do work to make it look like a variable of the requested size (like shifting the bits). So you better read the data in machine sized words, and then use the AND operation to check for 0s. Also, when scanning through the string, make sure you start at an aligned start address.

提交回复
热议问题