Malina Malina - 1 year ago 108
C Question

Is strncmp faster than strcmp


slower than
as one can give pre-calculated string length to it, but
does not receive such information ?

I am writing an interpreter. I am aware that these functions are both optimized. I wonder what will be the better approach (in terms of performance), as I will do scan anyway and I will know offset positions hence lengths.

R.. R..
Answer Source

They do different things, so comparing them directly does not make sense. strncmp compares the first n (or fewer, if the string ends sooner) characters of a string. strcmp compares whole strings. If n is sufficiently large that strncmp will compare the whole strings (so that the behavior becomes effectively the same as strcmp) then strncmp is likely to be moderately slower because it also has to keep track of a counter, but the difference might or might not be measurable or even present in a given implementation. For example an implementation of strcmp could just pass SIZE_MAX as the value for n to strncmp.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download