bashprintf

printf() is too slow in bash


I was trying to output numbers in hex with bash. The code below finishes in roughly 150 milliseconds:

count=0
for a in {0..15999}; do
  ((count++))
  output=$a 
  if (( count == 15 )); then
    echo -e "$output"
    ((count = 0))
  else
    echo -en "$output "
  fi
done

But if I change output=$a to output=$(printf "%04x\n" $a) the code ends in 15.8 seconds. It's about 100 times slower. What it is wrong here? Is there a better way to solve this?


Solution

  • $(...) spawns a subshell to run the command in. Spawning a subshell is slow. Use printf -v output '%04x' "$a" instead.