Skip to content

Conversation

@bwest2397
Copy link
Contributor

uuid.uuid4().hex, used in Element.__init__ to define self._id, is considerably slower than binascii.hexlify(os.urandom(16)).decode(). uuid4 uses os.urandom(16) under the hood when creating a cryptographically-secure UUID, so creating UUIDs for Element-class objects using hexlify leads to a dramatic speed-up (I found about ~60%), which has implications for subclasses of Element. No new requirements are needed as binascii is already in the Python standard library, so this is essentially a free, pretty big speed bump (especially when considering that some Element subclasses in folium themselves create child instances of Element when instantiated).

  • self._id = uuid4().hex:
In [1]: from branca.element import Element
   ...: %timeit -n 1000000 Element()
2.5 µs ± 8.56 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
  • self._id = hexlify(urandom(16)).decode():
In [1]: from branca.element import Element
   ...: %timeit -n 1000000 Element()
1.06 µs ± 1.86 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Copy link
Member

@Conengmo Conengmo left a comment

Choose a reason for hiding this comment

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

Thanks for your PR, and great description. To be honest I don't think the time savings are that dramatic, we're talking about 1.5 ms when creating 1000 elements, which I don't think users will notice. But still, it's a saving and this change seems quite safe to me. I don't suppose any users will notice that we have a different implementation for _id, since that field is randomly generated anyway.

@Conengmo Conengmo merged commit 629ed34 into python-visualization:master Oct 21, 2021
@bwest2397 bwest2397 deleted the uuid-speedup branch October 21, 2021 18:34
Conengmo pushed a commit to python-visualization/folium that referenced this pull request Jan 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants