Jump to content
  • Advertisement
Sign in to follow this  
CuppoJava

How to optimize an immutable class?

This topic is 3740 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I designed an immutable class for other people to use. And I'm wondering if there's any way to optimize it for performance. ie.
class MyImmutableList
{
  final List myList;
  public MyImmutableList(List list)
  {
    myList = list;
  }
 
  public MyImmutableList append(Item item)
  {
    List copy = myList.copy();
    copy.append(item);
    return new MyImmutableList(copy);
  }
}
But I find that many times, other people use the class like this: someList = someList.append(item); So in a case like this, append() is unnecessarily making a copy of the list. Is there anyway to optimize this? Thanks -Cuppo

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by Zipster
Well, for starters, making the immutable list actually immutable instead of allowing people to add items to it would be good :)


The list is immutable, since you can't add new items to it [smile] as for the OP, you can consider the usual construct in functional languages where a list is either empty or an element and a list.


class MyImmutableList
{

final MyImmutableList tail;
final Item item;

private MyImmutableList(MyImmutableList tail, Item item)
{
this.tail = tail;
this.item = item;
}

public static MyImmutable Empty() { return null; }
public static MyImmutableList Append(MyImmutableList list, Item item)
{
return new MyImmutableList(list, item);
}

public static MyImmutableList Tail(MyImmutableList list)
{
if (list == null) throw Whatever;
else return list.tail;
}

public static Item Head(MyImmutableList list)
{
if (list == null) throw Whatever;
else return list.item;
}
}

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Quote:
Original post by Zipster
Well, for starters, making the immutable list actually immutable instead of allowing people to add items to it would be good :)


The list is immutable, since you can't add new items to it [smile]

What, I never said that [wink] Yeah I erased it while you were replying because I realized that it was indeed immutable.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!