简体   繁体   中英

Is there any performance gain when using Indexer for Objects?

Suppose if I have to make three objects for a class flyweight, what is the difference between making an object like this

flyweight f1=new flyweight();
flyweight f2=new flyweight();
flyweight f3=new flyweight();

and like this?

public class flyweight
{
    flyweight[] obj = new flyweight[3];
    public flyweight this[int index]
    {
        get{
            if (index < 3) {
                obj[index] = new flyweight();
            }
            return obj[index];
        }
    }
    public void display() {
        Console.WriteLine("this is a object");
    }
    public void load() {
        flyweight f = new flyweight();
        for (int i = 0; i < 3; i++) {
            f[i].display();
        }
    }
}

Is there any performance gain when we use Indexer for creating objects?

An index property is compiled as a simple public flyweight get_Item(int index) method. Calling a method is not faster than accessing variables f1 , f2 and f3 directly (although I do not have proof for that).

If you optimize on this level, without evidence of performance issues, you'll probably end up with a slower application full of bugs because your application layout is a mess.

If anything you could use a double approach, using both instance variables and an array:

var f1 = new flyweight();
var f2 = new flyweight();
var f3 = new flyweight();
var flyweights = new[] { f1, f2, f3 };

This allows to use specific instances if you need to, and iterate over all of them where that might be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM