'How to mask action faster in Python3
I am using below function for millions of time in read/write sqlitedb . And it is now a major bottleneck . How I can make it faster for similar result ? I compiled it to module so but still slower part .
BEST
def mask_np(byt):
# Use same function in both directions. Input and output are bytes
# objects.
mask = b'maskstringtoserve'
lmask = len(mask)
return bytes(c ^ mask[i % lmask] for i, c in enumerate(byt))
Solution 1:[1]
Solution is to use numpy:
def mask_numpy(val: bytes) -> bytes:
arr = np.frombuffer(val, dtype=np.int8)
length = len(value)
np_mask = np.tile(np.frombuffer(mask, dtype=np.int8), round(length/mask_length+0.5))[:length]
masked = arr ^ np_mask
return masked.tobytes()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 2adnielsenx xx |
