|
| 1 | +""" |
| 2 | +Tests the performance of all of the solutions listed in the following article: |
| 3 | +https://therenegadecoder.com/code/how-to-convert-an-integer-to-a-string-in-python/ |
| 4 | +""" |
| 5 | + |
| 6 | +from test_bench import test_bench |
| 7 | + |
| 8 | + |
| 9 | +def control(_): |
| 10 | + """ |
| 11 | + Provides a control scenario for testing. In this case, none of the functions |
| 12 | + share any overhead, so this function is empty. |
| 13 | +
|
| 14 | + :param _: a placeholder for the int input |
| 15 | + :return: None |
| 16 | + """ |
| 17 | + pass |
| 18 | + |
| 19 | + |
| 20 | +def convert_by_type_casting(integer: int) -> str: |
| 21 | + """ |
| 22 | + Converts an integer to a string by type casting. |
| 23 | +
|
| 24 | + :param integer: an integer |
| 25 | + :return: the integer as a string |
| 26 | + """ |
| 27 | + return str(integer) |
| 28 | + |
| 29 | + |
| 30 | +def convert_by_f_string(integer: int) -> str: |
| 31 | + """ |
| 32 | + Converts an integer to a string using f-strings. |
| 33 | +
|
| 34 | + :param integer: an integer |
| 35 | + :return: the integer as a string |
| 36 | + """ |
| 37 | + return f"{integer}" |
| 38 | + |
| 39 | + |
| 40 | +def convert_by_interpolation(integer: int) -> str: |
| 41 | + """ |
| 42 | + Converts an integer to a string using string interpolation. |
| 43 | +
|
| 44 | + :param integer: an integer |
| 45 | + :return: the integer as a string |
| 46 | + """ |
| 47 | + return "%s" % integer |
| 48 | + |
| 49 | + |
| 50 | +def main() -> None: |
| 51 | + """ |
| 52 | + Tests the performance of all the functions defined in this file. |
| 53 | + """ |
| 54 | + test_bench( |
| 55 | + [ |
| 56 | + control, |
| 57 | + convert_by_type_casting, |
| 58 | + convert_by_f_string, |
| 59 | + convert_by_interpolation |
| 60 | + ], |
| 61 | + { |
| 62 | + "Zero": [0], |
| 63 | + "Single Digit": [5], |
| 64 | + "Small Number": [1107321], |
| 65 | + "Massive Number": [2 ** 64] |
| 66 | + } |
| 67 | + ) |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + main() |
0 commit comments