3 ms·
You say strlen() but you probably mean "code has to iterate all the string elements". This doesn't happen 3 times, though: > char foo[9]; strcpy(foo,"abc"); s
by kyberias 8y ago
You say strlen() but you probably mean "code has to iterate all the string elements".
This doesn't happen 3 times, though:
> char foo[9]; strcpy(foo,"abc"); strcat(foo,"1234");
Strcpy has to iterate through all the elements because it copies them. This would happen regardless. It doesn't do strlen.
Strcat has to find the end of the destination string, so it has to iterate (or call strlen). Then it's just strcpy again.
Instead of 3 strlens, there is 1.
Do you not understand how C string/arrays work, or why do you insist on 3 strlens?
- WalterBright 8y agoSee my other reply to this above.
- tjoff 8y ago> Strcpy has to iterate through all the elements because it copies them. This would happen regardless. It doesn't do strlen. Iterate all the elements and copy a fixed size is two very different things. strcpy has to read, byte for byte, and check it for null (which is exactly what strlen does). A "real" copy would just blindly copy a chunk of memory with no other processing on it. The speed difference is huge.
- WalterBright 8y agoYou're right. I apologize for using strlen metaphorically rather than literally.
- jibal 8y ago> You say strlen() but you probably mean "code has to iterate all the string elements". Yes, but that's much more expensive than a memcpy (of the two source strings) or just knowing the length (of the string in the target buffer). > Strcpy has to iterate through all the elements because it copies them. This would happen regardless. No, it wouldn't; memcpy is generally a lot faster than strcpy. > Do you not understand how C string/arrays work Do you not understand that he's written a few C compilers, and designed and implemented a language that is known for its runtime compatibility with C? > or why do you insist on 3 strlens? Um, you already noted that he really means "code has to iterate all the string elements". What he should have said is that you have to find 3 NULs. That's an expensive operation even when you're copying the string while finding it.