0

I am trying to solve an optimization problem and to find the most efficient way of performing the following commands:

whois -> sed -> while (exit while) ->perform action

while loop currently look like

while [x eq smth]; do
x=$((x+1))
done

some action

Maybe it is more efficient to have while true with an if inside (if clause the same as for while). Also, what is the best case using bash to evaluate the time required for every single step?

4
  • 1
    Do you have reason to believe that this is in anyway a bottleneck for your task? Commented Feb 11, 2013 at 16:48
  • If you're that concerned about efficiency in a shell script, perhaps you should be writing this in C or C++ or something else rather than an interpreted scripting language. Commented Feb 11, 2013 at 16:59
  • The sed (or any other child process) is probably your main overhead, rewriting the loop is unlikely to make a significant difference. Consider using shell expansion instead of sed, or write the whole lot in awk, or maybe even perl if you have complex code. Commented Feb 11, 2013 at 17:29
  • @tvalberg the script includes curl/etc, however will consider option regarding c/c++. In such a case, what would be the most efficient programming language that would contain curl/find/substr? Commented Feb 11, 2013 at 19:57

2 Answers 2

2

The by far biggest performance penalty and most common performance problem in Bash is unnecessary forking.

while [[ something ]]
do
    var+=$(echo "$expression" | awk '{print $1}')
done

will be thousands of times slower than

while [[ something ]]
do
    var+=${expression%% *}
done

Since the former will cause two forks per iteration, while the latter causes none.

Things that cause forks include but are not limited to pipe | lines, $(command expansion), <(process substitution), (explicit subshells), and using any command not listed in help (which type somecmd will identify as 'builtin' or 'shell keyword').

Sign up to request clarification or add additional context in comments.

1 Comment

So what would you suggest for such script evaluation, using simple date ?
0

Well for starters you could remove $(, this creates a subshell and is sure to slow the task down somewhat

while [ x -eq smth ]
do
  (( x++ ))
done

1 Comment

$((expr)) is unrelated to $(expr) and does not cause a subshell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.