Avoid append value on Success.filter if the predicate doesn’t hold

I was chasing a bug for a couple of days that was causing gc pressure. I’ve measured a couple of different implementations and monitoring allocation rate and histograms (number of instances and memory).
I’ve seen that a higher number of [C instances were being instantiated in a particular implementation and recently I figured out that the origin was the use of Try.filter ( Success.filter to be more precise).
When the predicate doesn’t hold, a new Failure with an NoSuchElementException wich message is created appending value.toString (in my case the value was a heavy object).

IMHO this isn’t transparent and in my particular case it was causing a bug that was hard to track and see at first sight.
Although I was able to find a very simple solution moving the predicate inside the foreach that was after the filter , this could be different in some case, so I was wondering if it would be better to avoid the append (considering that is mainly useful for debug purposes), what do you think?

(I’ve created this same topic in scala users a couple of days ago but then I realize that maybe it fits better in this forum, if it not please delete this topic).


It could use a custom UnsatisfiedPredicateException with writableStackTrace turned off. The exception could hold a reference to the offending value.