miriam_e: from my drawing MoonGirl (Default)
[personal profile] miriam_e
This was an interesting diversion today. I needed a way to construct a long string from a smaller one repeated many times, so I tried a few ways of my own devising and found many more on the net. There were some surprising ways to do this, but the really big surprises came when I decided to time them so as to work out which is the fastest. The winner is yes. That really surprised me. (Another big surprise was perl -- it ties for fastest.) The next two fastest are sed -E (extended regex) and plain sed.

NOTE: The time values I give below are the times to make a string repeating "test" 100,000 times.

EDIT: I have a late addition that uses perl. It surprisingly runs as fast as the yes/head/tr pipeline. I've added it at the bottom.

Here is my list of solutions:

yes is a command that endlessly prints out a string
yes "test" | head -n 10 | tr "\n" " " ; echo
0.044 seconds

A tricky way to use printf
printf 'test %.0s' {1..10} ; echo
0.190 seconds

printf to a variable
printf -v testvar 'test %.0s' {1..10}
0.169 seconds

A slightly different way to printf to a variable
printf -v testvar '%s ' test$_{1..10}
0.194 seconds

An echo {} hack.It requires that $nothing1 $nothing2 $nothing3 ... be non-existent variables.
echo test$nothing{1..10}
0.217 seconds

simple {} sequence loop
for i in {1..10} ; do echo -n "test " ; done ; echo
1.482 seconds

two simple seq loops
for i in $(seq 10) ; do echo -n "test " ; done ; echo
1.617 seconds
for i in `seq 10` ; do echo -n "test " ; done ; echo
1.367 seconds

simple c-style loop
n=10 ; for (( c=1; c<=n; c++)) ; do echo -n "test " ; done ; echo
2.130 seconds

a weird one
echo 'test'{,,,,,,,,,}


using awk for part
seq 10 | awk '{printf "test "}'; echo
0.769 seconds

awk only
awk 'BEGIN{for (n=0; n<10; n++) printf "test "; print ""}'
0.880 seconds

using sed for part
seq 10 | sed -E 's/.+/test/' | tr '\n' ' ' ; echo
0.089 seconds

or
seq 10 | sed 's/.*/test/' | tr '\n' ' ' ; echo
0.096 seconds

or
seq 10 | sed -z 's/[^\n]*\n/test/g' ; echo
0.173 seconds

using perl
perl -e 'print "test " x 10; print "\n"'
0.046 seconds
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

miriam_e: from my drawing MoonGirl (Default)
miriam_e

February 2026

S M T W T F S
123 4567
891011121314
15161718192021
22232425262728

Style Credit

Expand Cut Tags

No cut tags
Page generated Wednesday, 4 February 2026 03:10 pm
Powered by Dreamwidth Studios