Bartc said:
You admit this simple task can be accomplished with 3 calls to simple
building block functions in the library. Functions which are tried and
tested.
If the task was to compare the shorter string with the /end/ of the longer
string instead, a simple rearrangement of the same 3 calls would suffice.
The dedicated code on the other hand would need rewriting. All for a
comparison which for all we know is only done once in the program.
(The original problem was to determine, for two arbitrary strings,
whether either one is an initial substring of the other.)
Maybe it's done only once in the program, or maybe it's done a billion
times with multi-kilobyte strings.
There is no solution that *just* uses library functions; you have to
write some code to call them. A solution that calls strlen() on both
strings must scan both strings to the end; a hand-written solution can
ignore the excess characters of the longer string, which *might* be a
significant performance improvement.
If you're sure performance isn't going to be an issue (the strings
never differ much in length, or you know strlen() is optimized better
than any portable hand-written code you could write, or the function
is called rarely enough that it's not going to be a performance
bottleneck), then go ahead and write the simpler code that calls
strlen() on both strings. Otherwise, the hand-written version can be
a perfectly reasonable optimization.
Library functions are tried and tested, but they aren't a magic bullet
-- and any code you write had better be tried and tested itself
(though not as extensively as the standard library functions, or even
a particular implementation of them). An extreme example: on some
programming Q&A forum, somebody asked how to find the minimum element
of a array without using a loop. The proposed solution was to sort
the array and take the first element.