21

In search of the smartest, most efficient and readable way to do the below:

int one = 1, two = 2;
int larger = one < two?two:one;

I prefer(or a variadic version of the below):

int largest(one,two){return one<two?two:one;}
int larger = largest(one,two);

But dart has no inline or macro.

With List:

var nums = [51,4,6,8];
nums.sort();
in largest = nums.last

Or(Thank you, Günter Zöchbauer):

print([1,2,8,6].reduce(max));

Using math library:

import 'dart:math';
int largest = max(21,56);

Probably the best, but how efficient is max in comparison to the first approach?

Why the question?
With the first approach I must check comparisons are done right for each of them;hundreds of them sometimes. With the second, only one function to verify, but hundreds of function calls.

TastyCatFood
  • 1,632
  • 1
  • 15
  • 27

1 Answers1

35

I'm pretty sure just

import 'dart:math';
int largest = max(21,56);

is the best way. It is small enough to be inlined by a compiler (dart2js, VM) and it is the least surprise for the reader. For a custom implementation the reader had to investigate the function to be sure about what it does.

For collections of values I find this the most elegant way

from https://stackoverflow.com/a/20490970/217408

import 'dart:math';

main(){
  print([1,2,8,6].reduce(max)); // 8
  print([1,2,8,6].reduce(min)); // 1
}

Reordering a list just to get the min/max is quite inefficient

var nums = [51,4,6,8];
nums.sort();
in largest = nums.last
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 3
    Only caveat is that `min` and `max` from `dart:math` are only defined on numbers. They are pretty efficient on those, considering that they handle `min(0.0, -0.0)` -> -0.0 and returns NaN if either value is NaN. I doubt they are as quick as `a – lrn Jan 21 '16 at 09:17