If you deeply care about performance, perhaps (a) Bash is not the best tool and (b) you should try different approaches and test them on your data. This being said, maybe associative arrays could help you.
Try this :
#!/bin/bash
declare -A array_test()
array_test=(["text1"]="" ["text2"]="" ["text3"]="" ["text4"]="" ["text5"]="")
text_to_search="text4"
if
[[ ${array_test[$text_to_search]+found} ]]
then
echo "Found!"
fi
Please note in this case I build the associative arrays with keys but empty values (no real use in setting the value to the same thing as the key and eating up more memory).
Another approach would be to sort your array, and use some kind of binary search. That would, of course, involve more code, and if Bash associative arrays are implemented efficiently, is likely to be slower. But, again, nothing beats testing on actual data to validate performance hypotheses.
If you have an associative arrays with information in the keys, you can use an expansion to use them the same way you would use values :
for key in "${!array[@]}"
do
do_something_with_the key
done
Also, you can build your array with a loop, which would be useful if you read your elements from a file or from the output of a command. As an example :
declare -A array_test=()
while IFS= read -r key
do
array_test[$key]=
done < <(command_with_output)
It is useful to note that an element set to a null (empty) value is not the same as an unset element. You can easily see that with the following expansion :
declare -A array_test=()
array_test[existing_key]=
echo ${array_test[existing_key]+found} # Echoes "found"
echo ${array_test[missing_key]+found} # Echoes nothing
The "${var+value}"
expansion use useful because it expands to nothing if the variable is unset, and to value
if it is set. It does not produce an error when using set -u
that catches attempts to expand unset variables.