开发者

How would you declare the OneToMany member variable

Which of the following declaration would be the right one to choose for allocating the right amount of memory. Option 1 has an initial collection capacity of 0 and Option 2 has an initial capacity of 10 and Option 3 doesn't declare anything.

If the underlying ORM provider loads these object eventually, wouldn't it be using a setEmails(..) method to set the values of the Collection. If so, would it make sense to just declare this as in Option 3, so that I can avoid unnecessary memory allocation.

Option 1
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Email> emails = new HashSet<Email>(0);

or

Option 2
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Email> emails = new HashSet<Email>();

or开发者_如何学Python

Option 3
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Email> emails;


That's microoptimization.

Technically, in terms of memory allocation they are ordered:

Option 3 better than Option 1 slightly better than Option 2

But still, Option 2 might be your best choice

  • the Set won't have to be expanded when you add items
  • your code will be easier to handle, since you won't have to check for null


If so, would it make sense to just declare this as in Option 3, so that I can avoid unnecessary memory allocation.

Well, you do also create entities. And because I like to use defensive style programming methods when working with bi-directional associations, like this:

public void addToEmails(Email email) {
    emails.add(email);
    email.setUser(this);
}

I tend to prefer Option #2 because I don't have to do the null check.

And honestly, I don't even think about the "cost" of instantiating an empty collection. This is very likely not what will kill my application performances.

If your application is becoming slow (do you even know why it is? Is it really a memory or GC problem? what did you diagnose or measure?), I'm pretty sure that there are more critical optimizations than this one to do. Actually, I bet my shirt on it.

And don't forget:

If you cannot measure it, you cannot improve it. --Lord Kelvin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜