How to determine the order of [Array [Byte]]?

Is implementation necessary from scratch? I could not find any matching implicit, not even in the latter case Implicits. seqDerivedOrdering obviously does not work, since Array not Seq .

+6
source share
3 answers

If you want it to be efficient, you will have to write your own (this handles null values, if you cannot accept any zeros, just use the long else block):

 val o = new math.Ordering[Array[Byte]] { def compare(a: Array[Byte], b: Array[Byte]): Int = { if (a eq null) { if (b eq null) 0 else -1 } else if (b eq null) 1 else { val L = math.min(a.length, b.length) var i = 0 while (i < L) { if (a(i) < b(i)) return -1 else if (b(i) < a(i)) return 1 i += 1 } if (L < b.length) -1 else if (L < a.length) 1 else 0 } } } 

Otherwise, you can pack .toSeq into a WrappedArray and defer it to a Seq comparison instead of a native scan. (This will lead to the boxing and unpacking of your bytes, which is why it is not efficient. Since byte-boxing is usually done by searching all the bytes in the table, it is not terribly inefficient, so you can leave it if you only process binary files with large load.)

+8
source

If you use brevity rather than raw performance:

 scala> Ordering.by((_: Array[Byte]).toIterable) res0: scala.math.Ordering[Array[Byte]] = scala.math.Ordering$$anon$7@8c9f531 
+7
source

You can implement very simple Ordering , which calls toSeq in a comapred array and calls seqDerivedOrdering . Converting to Seq should be nearly free in terms of performance.

+2
source

Source: https://habr.com/ru/post/895339/


All Articles