[Top][All Lists]

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

Re: [Help-bash] make function local

From: Peng Yu
Subject: Re: [Help-bash] make function local
Date: Sun, 19 Apr 2015 21:38:06 -0500

Hi Chet,

>> Eduardo A. Bustamante López wrote:
>>> Well, if your scripts are so simple, why use local functions at all?
>> ---
>>     Cleanliness, Hygiene...
> Please, let's not have this argument again.  I think you're all using the
> term `local function' to mean different things.
> You seem to be using the term to describe one-time-use functions (they're
> almost lambdas, but they have names).  If you define a function within
> another function's body, have it unset itself when it executes, and call
> it only from within the function where it's defined, you have something
> very close to one-time-use functions with function-only scope.
> However you use them, they share the name namespace as every other defined
> function, regardless of whether or not they are defined as part of the body
> of another function.  If you had a function defined in the global scope
> with the same name as your one-time-use function, it would be removed when
> the one-time-use function was declared.  I think this is what Greg and
> Eduardo mean, and in this sense they are correct: bash doesn't have local
> functions with separate namespaces from other defined functions.
> That's the difference: if you're careful with naming and rigorous about
> your calling conventions, your one-time-use functions are about as close
> as you can get to local functions in bash, but you have to pay attention
> to the declaration's side effects.

There is at least a runtime overhead for having too many unused
functions that are supposed to be "local" or in your word "lambda".
Despite that one can rename supposedly internal functions to names
that are unlikely to cause name collision via good naming convention,
it still can incur a significant performance overhead.

In this sense, I think that it is still necessary to consider make the
supposedly internal function "local" so that they would not slow down
function search in the global namespace.

~$ cat main_many.sh
#!/usr/bin/env bash

for i in $(seq -w $n)
  eval "function f$i { echo '$i'; }"

function g {
for i in $(seq -w $n | head -n 1000)
  f$i > /dev/null

time g

~$ ./main_many.sh 1000

real 0m0.032s
user 0m0.020s
sys 0m0.010s
~$ ./main_many.sh 10000

real 0m0.040s
user 0m0.029s
sys 0m0.011s
~$ ./main_many.sh 100000

real 0m0.490s
user 0m0.461s
sys 0m0.031s


reply via email to

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