Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed/adviseable to reuse a Collector?

I have quite a lot spots in my code which do:

someStream.collect(Collectors.toList()) 

where Collectors.toList() creates a new collector on every use.

This leads me to the question if it is allowed and advisable to do something like:

private final static Collector<…> TO_LIST = Collectors.toList() 

for every type I use and then make use of that single Collector like:

someStream.collect(TO_LIST) 

when a collector is required.

As the collectors are stateless and just a collection of functions and characteristics, I should think it should work, but OTOH, Collectors.toList() creates a new CollectorImpl<> on every call.

What are the downsides of reusing a Collector?

like image 855
glglgl Avatar asked May 09 '17 07:05

glglgl


1 Answers

I think this is more of a style question, but lets give some thoughts:

  • It seems to be common practice to not use such a CONST collector object. In that sense: doing so might surprise some readers, and surprising readers is rarely a good thing to do.
  • Then: few code can be just "copied" around (and probably shouldn't to avoid code duplication); but still: pointing to a distinct collector object might make it a bit harder for you to re-factor or re-use your stream constructs.
  • Beyond that: you stated it yourself; collector re-use depends on the a stateless implementation. So you make yourself dependent on any implementation being stateless. Probably not a problem; but maybe a risk to keep in mind!
  • Probably more important: on the surface, your idea looks like a nice mean for optimization. But well; when you worry about the "performance effects" of using streams, then that one single object creation of the final collector will "not cut it"!

What I mean with that: if you are worried of "wasting" performance; you would rather look into each and any line of code that uses streams to determine whether that stream is working with "enough" objects to justify the usage of streams in the first place. Those streams come with quite some overhead!

Long story short: the java community has yet to find "standard best practices" for streams; thus my (personal) two cent at this time: prefer those patterns that "everybody" is using - avoid doing your own thing. Especially when it is "performance related".

like image 51
GhostCat Avatar answered Sep 21 '22 12:09

GhostCat