Sorting an array once in a function which is called many times
Is this possible?
I have a function which accepts a user string and then splits into an array of words. I'm going to sort the array and de-duplicate it.
However, it will be used in a function which is called in an iterative step. It actually iterates over a database and checks for each word in the user defines string in each field.
I would like to only开发者_C百科 sort and de-dup the array once but call the function many for that particular instance of the class. Should I just store the sorted array in a static instance variable?
Thanks for your time
My code is something like this (pseudo-code):
public class searchAssistant{
private float mScores[][];
private Cursor mCursor;
public searchAssistant(Cursor c){
mCursor = c;
}
private float scoreType1(String typeFromCursor, String typeFromUser){
if (typeFromCursor == typeFromUser) {return 1}
else {return 0}
}
//similar method for type scoreType2 but sorting an array
private int[] scoreAll(){
int 1 = 0;
do {
mScores = ScoreType1(mCursor.getString(), smomeString) + scoreType2(...);
itr++;
} while(cursor.moveToNext)
return mScores;
}
}
is this the wrong way to be doing things?
No. Change the signature of the method called multiple times to make it accept the array, and compute the array before calling the method:
Instead of
String s = "...";
while (someCondition) {
someMethodCalledMultipleTimes(s);
}
Use something like this:
String s = "...";
String[] array = computeTheArrayFormTheString(s);
while (someCondition) {
someMethodCalledMultipleTimes(array);
}
Should I just store the sorted array in a static instance variable
"Static instance variable" is an oxymoron.
You almost certainly shouldn't store it in a static variable.
It might make sense to store it in an instance variable. This may have consequences for thread safety (don't know if that's relevant to your situation).
If the iteration is performed by a function defined in the same class, it might make sense to do the sorting inside that outer function and simply pass the sorted array to the inner function every time you call it.
If all of this is happening in the same Thread, you can use a ThreadLocal
to save the sort state:
private static final ThreadLocal<Boolean> SORT_STATE = new ThreadLocal<Boolean>(){
protected Boolean initialValue(){return Boolean.FALSE;}
};
public void doSomething(String[] array) {
if(!SORT_STATE.get().booleanValue()){
// then sort the array here
SORT_STATE.set(Boolean.TRUE);
}
// now do everything else
}
You would store it in a non-static instance variable (there is no such thing as static instance variable - these are opposite things).
If your application is not multithreaded you can do the sorting and dedupping the first time and than store the result. (Same if it's multithreaded, but then you need to use locking of some sort).
精彩评论