Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace with .lengthCompare warning

IntelliJ keep suggesting to replace .length == X with .lengthCompare(X) == 0. Why is that better? Don't quite get it, since the suggested changes are more verbose.

enter image description here

like image 630
Yuchen Avatar asked Mar 07 '18 21:03

Yuchen


1 Answers

It is more efficient.

Since length is a linear operation on some collections like List, doing x.length == 3 would need to compute the length first and then compare it with the value. On the other hand .lengthCompare would terminate computing the length once it finds that the comparison is wrong already.

like image 70
Sleiman Jneidi Avatar answered Sep 21 '22 08:09

Sleiman Jneidi