Reputation: 313
Does it make sense to reuse the same array instead of declaring in .collectInto
?
return loadSortedSparseNumbersObservable()
.collectInto(
new numbers[1000],
(array, number) -> {
int index = computeTrueIndex(...);
array[index] = number;
}
)
.map(array -> );
We can probably replace the code above with something like:
long[] array = new long[700];
return loadSortedSparseNumbersObservable()
.doOnNext(
Arrays.fill(array, 0L),
(array, number) -> {
int index = computeTrueIndex(...);
array[index] = number;
}
)
.toCompletable()
.andThen(Single.just(array))
.map(array -> );
I don't really like mutating object though.
Upvotes: 3
Views: 117
Reputation: 12097
Your second example has more operators thus potentially more overhead and of course is uglier to read and understand.
The big gotcha in both your examples is that the returned Observable
is not reusable safely. Concurrent calls to that same Observable
would interact on the array. The safe way to do that is to create a new array for every subscription. Use collect
instead of collectInto
:
return loadSortedSparseNumbersObservable()
.collect(
() -> new numbers[1000],
(array, number) -> {
int index = computeTrueIndex(...);
array[index] = number;
}
)
.map(array -> );
Upvotes: 1
Reputation: 186
The concern in modifying the array in-place is thread-safety. Arrays in Java are pass-by-reference so any reuse/modification of an array could cause concurrency problems in other parts of a program.
The question, though, doesn't give insight as to the structure or function of the code that is using this particular array, so there may be an application-specific reason to modify in-place. Likewise, there may be a very compelling reason not to.
Upvotes: 0