Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize withAll on MutableIntBagFactoryImpl and ImmutableIntBagFactoryImpl #1372

Closed
donraab opened this issue Aug 13, 2022 · 4 comments · Fixed by #1376
Closed

Optimize withAll on MutableIntBagFactoryImpl and ImmutableIntBagFactoryImpl #1372

donraab opened this issue Aug 13, 2022 · 4 comments · Fixed by #1376

Comments

@donraab
Copy link
Contributor

donraab commented Aug 13, 2022

The code currently in withAll on both mutable and immutable implementations calls toArray on IntStream which if the Stream is very large can be extremely expensive and won't take advantage of a Bag's ability to store duplicates as simply increments in a count.

Current mutable factory code:

public MutableIntBag withAll(IntStream items)
{
    return this.with(items.toArray());
}

Current immutable factory code:

public ImmutableIntBag withAll(IntStream items)
{
    return this.with(items.toArray());
}

It would be much better to simply iterate over the Stream and add the results to a HashBag, converting to an ImmutableBag in the immutable factory.

@TheJavaGuy
Copy link
Contributor

TheJavaGuy commented Aug 15, 2022

I will do it. Very probably this method in the ImmutableIntBagFactoryImpl also must be refactored not to use toArray:

@Override
public ImmutableIntBag withAll(IntIterable items)
{
    if (items instanceof ImmutableIntBag)
    {
        return (ImmutableIntBag) items;
    }
    return this.with(items.toArray());
}

@donraab
Copy link
Contributor Author

donraab commented Aug 15, 2022

Hi @TheJavaGuy, thanks for volunteering! Yes, refactoring this method makes sense as well. Thank you for looking around the code! I've assigned the issue to you.

@TheJavaGuy
Copy link
Contributor

For mutable Bags it’s easy fix. But for immutable ones I don’t see the way out without bigger changes. In the end the only way to create immutable bag (e.g. ImmutableIntHashBag) is either:

  • through constructor private ImmutableIntHashBag(int[] newElements), or
  • through overloaded withAll/ofAll which in the end of the chain must call constructor

To call the constructor array must be filled, and I’m back to square one :(

@donraab
Copy link
Contributor Author

donraab commented Aug 17, 2022

I think it would be fine for the Immutable factory to call the Mutable factory with the primitive Stream and then call toImmutable() at the end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants