Search code examples
javaandroidperformancedesign-patternsfinal

Efficient Adapter implementation


I have in my code two types for Adapter implementations and I'm not sure which one is better.

Here is my updater pattern:

public View getView(int position, View convertView, ViewGroup parent) {
    Updater content;
    if(convertView == null) {
        final TextView msg = new TextView(parent.getContext());
        content = new Updater() {
            public void update(...) {
                // code to update the control msg
            }
        };
        convertView = msg;
        convertView.setTag(content);
    } else {
        content = (Updater)convertView.getTag();
    }
    content.update(...);
    return convertView;
}

// ...

private interface Updater {
    void update(...);
}

And here is my ViewHolder pattern:

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView == null) {
        convertView = inflater.inflate(...);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder)convertView.getTag();
    }
    holder.setData(...);
    return convertView;
}

// ...

private class ViewHolder {
    public final TextView text;

    public ViewHolder(final View owner) {
        text = (TextView)owner.findViewById(R.id.text);
    }

    public void setData(...) {
        // ...
    }
}

I'm wondering which one is more effency? I could also implement the Updater interface in a more complex control, so it is simpler to update differnt controls in a common way. So I could just cast the convertView to my interface without using getTag(). But in the code above I use a final variable which is defined outside of my interface implementation. Can somebody tell me if this can make performance problems? I don't know what happens internal in java with a final variable.

If my updater pattern is bad please tell me, why I should use the ViewHolder pattern except that this pattern is from Google IO.


Solution

  • Decisions like this have almost no effect on performance. Both solutions are equally efficient. The final keyboard may actually increase performance by allowing the compiler to make certain optimizations, but they will be certainly unoticeable.