[llvm-dev] [PATCH] strlen -> strnlen optimization

Joerg Sonnenberger via llvm-dev llvm-dev at lists.llvm.org
Sun Feb 7 04:04:41 PST 2016


On Sat, Feb 06, 2016 at 11:05:14PM -0500, Michael McConville via llvm-dev wrote:
> This addition converts strlen() calls to strnlen() when the result is
> compared to a constant. For example, the following:
> 
> strlen(s) < 5
> 
> Becomes:
> 
> strnlen(s, 5) < 5
> 
> That way, we don't have to walk through the entire string. There is the
> added overhead of maintaining a counter when using strnlen(), but I
> thought I'd start with the general case. It may make sense to only use
> this optimization with small constants. On the other hand, the impact of
> the counter may be negligible in many or most cases due to
> hardware-level optimizations.

This is an optimisation I am very vary of two two reasons:
(1) strnlen is only POSIX2008, so missing on many slightly older
systems.
(2) I do believe that the counting is quite harmful to the performance.
Additionally, I wouldn't be surprised if many systems don't consider
strnlen to be the fast path, so it would be even worse than using e.g.
memchr for this.

Joerg


More information about the llvm-dev mailing list