How to concatenate strings efficiently in bash

The naive implementation for concatenating strings in bash goes something like this:

#!/bin/bash

statement="1234567890"

result=""

for i in $(seq 1 100000)
do
  result=${result}${statement}
done

wc <<< ${result}

This takes around two minutes on a modern machine. This is slow. Very, very slow.

Instead you can build an intermediate array and use the star operator to expand it into a string. Make sure to change the input field seperator to empty, so that you don’t get spaces in between the individual entries:

#!/bin/bash

statement="1234567890"

for i in $(seq 1 100000)
do
statements[${#statements[@]}]=${statement}
done

IFS= eval 'result="${statements[*]}"'

wc <<< ${result}

This will run in a few hundred milliseconds. You get roughly three orders of magnitude speedup.

 

Leave a Reply

Your email address will not be published.