Assembling a faster strlen()
17 February 2008If you have coded something in C, I’m quite sure you have used the strlen() library function. It returns the length of a string. It couldn’t be easier, you probably know how to code it, but you just don’t bother to do it yourself (that’s why the libraries are there).
So… have you seen that code? Here it goes. Quite big, you’d say. I agree. Did you know that there is a assembly instruction to do that? Did you know that it has been available since the original 8086/8088 instruction set?
Here is the piece of inlined assembly ready to compile. Do your tests if you want to (I didn´t).
unsigned int strlen_asm(char *in) {
unsigned int eos;
asm(
"movl %1, %%edi;"
"mov $0, %%al;"
"repnz scasb;"
"movl %%edi, %0;"
:"=r" (eos)
:"r" (in)
:"%edi"
);
return eos - (unsigned int)in;
}
Edit: Oh, yep, the kernel guys are using the same approach
Leave a Reply
You must be logged in to post a comment.
2 Responses to “Assembling a faster strlen()”
February 17th, 2008 at 11:09 pm
Hello! How long! I thought that you had died!
I believed that strlen works doing something like this:
int strlen(char *str){
int c = 0;
while(str != ”){
str ; c ;
}
return c;
}
But it doesn’t seem to me very eficient… xD
This week we’ve started to learn the assembler for MIPS2000, so I don’t understand the code… yet…
Regards.
February 18th, 2008 at 4:55 pm
Actually, is even simpler :)
int i=-1; while(str[i ]); return i;
or, the uClibc approach