Skip to content

Commit

Permalink
Optimize IsSpace function for common non-whitespace characters
Browse files Browse the repository at this point in the history
The IsSpace function has been optimized for the more common case where a character is not whitespace. Previously, the function checked each whitespace character individually, which was not efficient for non-whitespace inputs as it required multiple comparisons.

The updated IsSpace function now first checks if the character is less than or equal to ' ' (the space character, which has the highest ASCII value among the whitespace characters). This single condition can quickly determine that most characters (those with ASCII values greater than ' ') are not whitespace, thus short-circuiting the evaluation for the most common case.

If the character is less than or equal to ' ', the function performs additional checks to see if it is either a space character or within the range of horizontal tab to carriage return ('\t' to '\r'), which are the remaining whitespace characters in the ASCII table.

This change assumes that most calls to IsSpace are for non-whitespace characters, as can be inferred from the usage patterns where IsSpace is often used in loops that parse strings until a non-whitespace character is encountered.
  • Loading branch information
Lőrinc committed Mar 9, 2024
1 parent fe0078c commit c15b5e2
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/util/strencodings.h
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ constexpr bool IsDigit(char c)
* @param[in] c character to test
* @return true if the argument is a whitespace character; otherwise false
*/
constexpr inline bool IsSpace(char c) noexcept {
return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v';
constexpr bool IsSpace(const char c) noexcept {
return c <= ' ' && (c == ' ' || (c >= '\t' && c <= '\r'));
}

/**
Expand Down

0 comments on commit c15b5e2

Please sign in to comment.