Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions fit_tool/definition_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,16 +114,14 @@ def to_bytes(self) -> bytes:
bytes_buffer.append(len(self.field_definitions))

# field definitions
for fd in self.field_definitions:
bytes_buffer += fd.to_bytes()
bytes_buffer += b''.join(fd.to_bytes() for fd in self.field_definitions)

# developer field definitions
if self.developer_field_definitions:
bytes_buffer.append(len(self.developer_field_definitions))

# developer field definitions
for fd in self.developer_field_definitions:
bytes_buffer += fd.to_bytes()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While the proposed change to use b''.join is a good optimization, the overall approach of building up a bytearray piece by piece can be further improved. A more idiomatic and often more efficient pattern in Python for constructing byte strings is to build a list of all the bytes components and then call b''.join on the list just once at the end.

This avoids the overhead of bytearray and its potential reallocations, and makes the code's intent clearer. I'd suggest refactoring the entire to_bytes method to follow this pattern. Here's what it could look like:

def to_bytes(self) -> bytes:
    endian_symbol = '<' if self.endian == Endian.LITTLE else '>'
    parts = [
        b'\x00',  # reserved
        b'\x00' if self.endian == Endian.LITTLE else b'\x01',  # architecture
        struct.pack(f'{endian_symbol}H', self.global_id),  # global id
        bytes([len(self.field_definitions)]),  # field count
    ]

    parts.extend(fd.to_bytes() for fd in self.field_definitions)

    if self.developer_field_definitions:
        parts.append(bytes([len(self.developer_field_definitions)]))
        parts.extend(fd.to_bytes() for fd in self.developer_field_definitions)

    return b''.join(parts)

This change would make the whole method more cohesive and performant.

bytes_buffer += b''.join(fd.to_bytes() for fd in self.developer_field_definitions)

return bytes(bytes_buffer)

Expand Down