bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: efficient way to use matched string in variable substitution


From: Greg Wooledge
Subject: Re: efficient way to use matched string in variable substitution
Date: Mon, 23 Aug 2021 15:57:59 -0400

On Mon, Aug 23, 2021 at 12:41:58PM -0700, L A Walsh wrote:
> 
> 
> On 2021/08/23 12:10, Greg Wooledge wrote:
> > On Mon, Aug 23, 2021 at 11:36:52AM -0700, L A Walsh wrote:
> > > Starting with a number N, is there
> > > an easy way to print its digits into an array?
> > 
> > "Easy"?  Or "efficient"?  Your subject header says one, but your body
> > says the other.
> Efficient, in my vocabulary, also includes my time in coding, typing
> and remembering ... i.e. it's not just limited to computer time. :-)
> 
> However, thanks for the examples!  I do appreciate them!

Well, the most important thing here is that your first working example
only works on input strings which contain no whitespace or globbing
characters, because you're using word splitting.  As long as your input
is a "number", this works.  But if you want to use this same function
on an arbitrary input string, it will not.

The proposed variant using ${input//?/& } (in a future version of bash)
will have the same issue.

I wrote another example after sending the last email.  Well, two actually,
but they're almost identical:


unicorn:~$ f5() { local i n=${#1} arr; while ((i < n)); do arr[i]="${1:i:1}"; 
((i++)); done; }
unicorn:~$ time for ((i=1; i<=10000; i++)); do f5 682390; done
real 0.420  user 0.410  sys 0.000


unicorn:~$ f6() { local i n=${#1} arr; for ((i=0; i<n; i++)); do 
arr[i]="${1:i:1}"; done; }
unicorn:~$ time for ((i=1; i<=10000; i++)); do f6 682390; done
real 0.397  user 0.387  sys 0.000


They're doing the same basic thing, but it seems the C-style for syntax
is a little more efficient than an equivalent while loop.

f6 is the fastest one I came up with which works on arbitrary strings.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]