Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid unnecessary strlen + memcmp call #94

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jserv
Copy link
Contributor

@jserv jserv commented Nov 23, 2024

Using strncmp() instead of strlen() combined with memcmp() not only reduces the overhead of multiple function calls but also takes advantage of compiler optimizations, such as implicit function inlining.

Using strncmp() instead of strlen() combined with memcmp() not only
reduces the overhead of multiple function calls but also takes advantage
of compiler optimizations, such as implicit function inlining.
@fuhsnn
Copy link
Owner

fuhsnn commented Nov 23, 2024

I was considering

__attribute__((always_inline))
static inline bool equal(Token *tok, char *op) {
  return strlen(op) == tok->len && !memcmp(tok->loc, op, tok->len);
}

or

#define equal(tok, op) (strlen(op) == (tok)->len && !memcmp((tok)->loc, op, (tok)->len))

Since most equal() calls are with compile time string literals, most strlen() are lowered to constants to compilers and the memcmp() can be further transformed to multi-bytes comparisons.

To illustrate:
https://godbolt.org/z/YjMK7az19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants