Skip to content

Instantly share code, notes, and snippets.

@hhsnopek
Last active January 7, 2017 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hhsnopek/c89c578cde44f09613859a44b1aca8e2 to your computer and use it in GitHub Desktop.
Save hhsnopek/c89c578cde44f09613859a44b1aca8e2 to your computer and use it in GitHub Desktop.
Bash Performance Test - Regex vs If/Else
# Requires: `bc`, `bash 4+`
#
# Example Output:
# Iterations 100,000
# regex: 34.570s
# if/else: 18.044s
#
# if/else is 47.8% faster than regex
declare -a arr=("/ock"
"/ock.html" "/ock.json"
"/ock?type=html" "/ock?type=json"
"/favicon" "/favicon.ico")
LIMIT=100000
count=0
START=$(date +%s.%N)
printf "Iterations %'.f" $LIMIT
printf "\n regex: "
# REGEX
while [ $count -lt $LIMIT ]; do
for i in "${arr[@]}"; do
path="$i"
if [[ "$path" =~ \/ock ]]; then
if [[ "$path" =~ \/ock(\.)(.*) ]] ||
[[ "$query" =~ (type\=)(html.*|json.*)? ]]; then
if [[ "$type" == 'json' ]]; then
continue
elif [[ "$type" =~ plain|html ]]; then
continue
fi
fi
elif [[ "$path" == '/favicon' || "$path" == '/favicon.ico' ]]; then
continue
else
echo 'unknown route'
continue
fi
done
let count=count+1
done
END=$(date +%s.%N)
REGEXDIFF=$(echo "$END - $START" | bc | awk -F"." '{print $1"."substr($2,1,3)}')
printf "%ss" $REGEXDIFF
START=$(date +%s.%N)
printf "\n if/else: "
count=0
# if/else
while [[ $count -lt $LIMIT ]]; do
for i in "${arr[@]}"; do
path="$i"
if [[ "$path" == '/ock' ]]; then
continue
elif [[ "$path" == '/ock.html' || "$path" == '/ock?type=html' ]]; then
continue
elif [[ "$path" == '/ock.json' || "$path" == '/ock?type=json' ]]; then
continue
elif [[ "$path" == '/favicon' || "$path" == '/favicon.ico' ]]; then
continue
else
continue
fi
done
let count=count+1
done
END=$(date +%s.%N)
IFELSEDIFF=$(echo "$END - $START" | bc | awk -F"." '{print $1"."substr($2,1,3)}')
printf "%ss\n\n" $IFELSEDIFF
DIFF=$(echo "$REGEXDIFF" - "$IFELSEDIFF" | bc -l)
DIVIDE=$(echo "$DIFF" / "$REGEXDIFF" | bc -l )
percentage=$(echo "$DIVIDE * 100" | bc)
echo -e "if/else is ${percentage::-19}% faster than regex"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment