Skip to content

Instantly share code, notes, and snippets.

@d630
Last active October 7, 2016 20:08
Show Gist options
  • Save d630/3ab887db1f5c013c6f2a9e3911cce597 to your computer and use it in GitHub Desktop.
Save d630/3ab887db1f5c013c6f2a9e3911cce597 to your computer and use it in GitHub Desktop.
bash: It's better to have many assoc. arrays with just a few keys instead of one with many keys
#!/usr/bin/env bash
AssocTest ()
{
create1 ()
{
declare -g -A Assoc
declare i
for ((i=${1?}; i <= ${2?}; i++))
do
Assoc[${i} k1]=$i
Assoc[${i} k2]=$i
done
#declare -p Assoc
}
create2 ()
{
declare i
for ((i=${1?}; i <= ${2?}; i++))
do
declare -g -A "Assoc_${i}=(
[k1]='${i}'
[k2]='${i}'
)"
#declare -p "Assoc_${a}"
done
}
retrieve1 ()
{
printf 'k1 :=%s\nk2 := %s\n' "${Assoc[${1?} k1]}" "${Assoc[${1} k2]}"
}
retrieve2 ()
{
declare -n assoc=Assoc_${1?}
printf 'k1 :=%s\nk2 :=%s\n' "${assoc[k1]}" "${assoc[k2]}"
}
{
time create1 0 "${1?}"
time create2 0 "$1"
} >/dev/null
retrieve ()
for x in {,,,,}${RANDOM} 111111 {1..1000} -1
do
"retrieve${1?}" "$x"
done >/dev/null
time retrieve 1
time retrieve 2
}
TIMEFORMAT=$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'
AssocTest 32767
# AssocTest 100
# AssocTest 1000
# AssocTest 10000
# vim: set ts=8 sw=8 tw=0 et :
@d630
Copy link
Author

d630 commented Oct 7, 2016

# GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)

real    0m2.084s
user    0m2.064s
sys 0m0.016s

real    0m1.857s
user    0m1.812s
sys 0m0.044s

real    0m0.148s
user    0m0.148s
sys 0m0.000s
bash: declare: `Assoc_-1': invalid variable name for name reference

real    0m0.050s
user    0m0.048s
sys 0m0.000s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment