performance: ${str#????} vs ${str:4}

Alin Mr almr.oss at outlook.com
Wed Jul 28 07:08:58 UTC 2021


Surprisingly, string matching is faster than substring-ing. 

# s is ':' repeated (6 * 2^i) times
s=$(s=::::::; i=12; while [ $i -gt 0 ]; do i=$((i-1)); s="$s$s"; done; echo "$s") \
hyperfine -w2 -S bbox-master/sh  'while [ "$s" ]; do s=${s#????}; done' 'while [ "$s" ]; do s=${s:4}; done'

Summary
  'while [ "$s" ]; do s=${s#????}; done' ran
    1.16 ± 0.00 times faster than 'while [ "$s" ]; do s=${s:4}; done'

The slowdown doesn't depend much on the skip parameter -- ${s:1} as well as ${s:16} are slower than corresponding pattern matches. There are jump points if $s gets much longer or much shorter.

I'm curious -- the SUBSTR code seems to check for quotes and CTLESC in vstr, so I guess... it can substring in unprocessed (shell) strings? When does this come into play -- it's not like one can write ${"a\\bc":2}?


More information about the busybox mailing list