3

Which way better?

if ("Pablo".equals(name) || "Marko".equals(name) || .. ); 

or

if (Sets.newHashSet("Pablo", "Marko", ..).contains(name));

Interest about memory using, performance, readabilty

mikewoe
  • 270
  • 2
  • 12
  • 1
    We can use switch instead of these.. – DhaRmvEEr siNgh Mar 26 '18 at 11:26
  • What is your real world problem where this even matters? I would assume that the compiler is smart enough to optimize the first case as much as it can. – Tim Biegeleisen Mar 26 '18 at 11:26
  • [You can measure it yourself](https://ericlippert.com/2012/12/17/performance-rant), and [related](https://stackoverflow.com/questions/4689334/how-can-i-check-if-an-element-exists-in-a-set-of-items), but... not too bad. – user202729 Mar 26 '18 at 11:27
  • either way, your first statement would be better written as: if ( "Pablo".equals(name) || "Marko".equals(name) || ... ) – Stultuske Mar 26 '18 at 11:27
  • 2
    For constant list of value, I like to use a `Collection` to check. But I only create one instance. I don't create a `Set` live. I feel this is a bit more readable but with correct method, this could be done the first way to. – AxelH Mar 26 '18 at 11:28
  • I'd say, factor it out to a function with a sensible name. Much more readable than some arbitrary expression, and you can always fiddle with the implementation later (if you really must). – Jorn Vernee Mar 26 '18 at 11:28
  • Please define, how you measure. What is `good`? What is `better`? – rollstuhlfahrer Mar 26 '18 at 11:29
  • @Stultuske thx for comment, i'm know this. just make quick example for showing idea – mikewoe Mar 26 '18 at 11:40

1 Answers1

5

The if statement will take linear time (O(n)), since it has n conditions to evaluate at the worst case.

The Set.contains variant will take linear time to construct the Set (adding n elements), but only constant time to search the Set for a specific value.

Therefore, if you run this condition multiple times (for the same set of values), creating the Set once and reusing it multiple times will be more efficient than running the if statement multiple times.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • It's type of condition to listener, so i think best would be make static Set with values and use it in if with .contains? – mikewoe Mar 26 '18 at 11:37