In an answer over on Stack Overflow, I provided a code sample to perform some small task referenced in the question. The original question had to do with the fastest-performing technique (so performance criteria are in play, here).
Another commenter/answerer suggested that making a POSIX-defined
system API call (in this case,
readdir) was not as fast as making a direct system call into the kernel (
syscall(SYS_getdents,...)) and the claimed performance difference is in the 25% range. (I didn't implement and re-benchmark; I believe that the performance could in fact be better.)
My question is about the performance characteristics of the proposed syscall-based solution and why they might be faster. I can think of a few reasons why performance might be better:
readdiris inherently more complicated than
readdir(which presumably calls
syscall(SYS_getdents,...)simply adds the overhead of indirection
readdironly returns one record (per kernel-call) versus
syscall(SYS_getdents,...)/getdents()` which returns (presumably) more than one record per kernel-call
I can't imagine that #1 above is true.
getdents are so similar that the implementation of
readdir in glibc simply can't have many more "true" system calls than a direct-invocation of
getdents() would invoke.
I can't imagine that #2 is true, either, since calling
readdir likely wraps
getdents and also
syscall(SYS_getdents,...) likely calls
getdents as well (the proposed answer specifically uses
syscall(SYS_getdents,...) instead of calling
getdents directly. It's possible that everything within glibc on Linux boils down to
syscall(syscallid, args) in which case #2 probably is true.
The last possibility seems to me to be the best explanation: fewer calls into the kernel simply results in faster performance.
Is there any specific explanation for why a "direct kernel call" would be measurably faster than calling a POSIX-defined function?