Optimize Dart Builder.writeListFloat32() for Float32List
The Dart flat_buffer Builder is slow when writing large Float32Lists because it iterates the elements one by one instead of copying the underlying memory buffer. The method can be optimized to special case when the given list is Float32List and then use faster memory copy operations. This aligns with the intentions of using typed data for cpu efficient code. Suggested code to change from:
int writeListFloat32(List<double> values) {
assert(!_inVTable);
_prepare(_sizeofFloat32, 1 + values.length);
final result = _tail;
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (final value in values) {
_setFloat32AtTail(tail, value);
tail -= _sizeofFloat32;
}
return result;
}
to:
int writeListFloat32(List<double> values) {
assert(!_inVTable);
_prepare(_sizeofFloat32, 1 + values.length);
final result = _tail;
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
if (values is Float32List && Endian.host == Endian.little) {
// Fast copying of Float32List
// Get the underlying bytes from Float32List (zero-copy view)
final floatBytes = values.buffer.asUint8List(values.offsetInBytes, values.lengthInBytes);
// Get the target location in our buffer
final targetOffset = _buf.lengthInBytes - tail;
// Bulk copy the float bytes directly to the buffer
final targetBytes = _buf.buffer.asUint8List(_buf.offsetInBytes);
targetBytes.setRange(targetOffset, targetOffset + floatBytes.length, floatBytes);
tail -= floatBytes.length;
} else {
// non-Float32List, iterate one element at a time
for (final value in values) {
_setFloat32AtTail(tail, value);
tail -= _sizeofFloat32;
}
}
return result;
}
If this makes sense I'd be happy to share a PR. Thanks!
This type of optimization sounds great -- can it be generalized to other types? A pr would be awesome
Hey, @jtdavis777 May I raise a PR for this? Please assign it to me. Thank you
@dataCenter430 I welcome any and all PRs on any issues, please do not wait for my approval :D
Hi, @jtdavis777 thanks for your trustworthy. 👍 okay, I will raise a PR for this issue soon. Then there is no review for my one PR: #8976. it was opened last week. Could you please review it when you have a chance? 🙏 Thanks again.
yes it is on my list! please see the discussion I opened as well :) I believe I tagged you in it for visibility. Things are moving a bit slower here than I'd like, but I love all the input and will work through it as I have time and space to do so!
This issue is stale because it has been open 6 months with no activity. Please comment or label not-stale, or this will be closed in 14 days.
This issue was automatically closed due to no activity for 6 months plus the 14 day notice period.