Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [p2-dev] Arrays versus List and immutability

This is a good point. Let's review that when we get to fix the implementation.


Inactive hide details for Thomas Hallgren ---09/14/2009 06:15:00 PM---On the call today we discussed pros and cons of using arrThomas Hallgren ---09/14/2009 06:15:00 PM---On the call today we discussed pros and cons of using arrays versus


From:

Thomas Hallgren <thomas@xxxxxxx>

To:

P2 developer discussions <p2-dev@xxxxxxxxxxx>

Date:

09/14/2009 06:15 PM

Subject:

[p2-dev] Arrays versus List and immutability




On the call today we discussed pros and cons of using arrays versus
collections. I'd like to address that briefly.

An IU must not change so whatever it returns must be read only. But
todays implementation does this:

    public IRequiredCapability[] getRequiredCapabilities() {
        return requires;
    }

which means that in theory I can do:

   IRequiredCapability[] caps = iu.getRequiredCapabilities();
   if(caps.length > 0)
      caps[0] = foobar;

and change the content of the IU. In order to make it truly read-only,
we must change into:

    public IRequiredCapability[] getRequiredCapabilities() {
        return (IRequiredCapability[])requires.clone();
    }

which is fairly expensive. What happens if we instead change the API so
that the IU returns a List? We need a read-only List implementation that
is backed by an array. The implementation is about 20 lines of code and
the only field is the array, so it's very lightweight. The fields in the
InstallableUnit doesn't need to change at all which means that its
memory consumption wouldn't change either.

    public List<IRequiredCapability> getRequiredCapabilities() {
        return new ImmutableArrayList(requires);
    }

No copy needed. The ImmutableList protects the array. This is a much
cheaper way to achieve immutability. If we're willing to sacrifice some
memory, the requires field could of course change to store the list itself.

Regards,
Thomas Hallgren

_______________________________________________
p2-dev mailing list
p2-dev@xxxxxxxxxxx
https://dev.eclipse.org/mailman/listinfo/p2-dev


GIF image

GIF image


Back to the top