###### tags: `Python` `Experiments` # String Reverse Experiment This blog will cover different ways to reverse a string in python and effective time and memory take for each method to find more optimized way. - timeit module is used to calculate the time taken to execute function - memory_profiler is used to get memory usage of particular function - memory_profile is an external module which can be installed using `pip install memory_profiler` - For more details visit [link](https://pypi.org/project/memory-profiler/) ```python from timeit import timeit from memory_profiler import memory_usage def str_rev(x): o = x[::-1] return o def str_rev_concat(x): o = "" for c in x: o = c + o return o def str_rev_format(x): o = "" for c in x: o = '{}{}'.format(c,o) return o def str_rev_reversed(x): return ''.join(reversed(x)) def str_rev_list(x): l=len(x) o=[None] * l o_idx = l-1 for c in x: o[o_idx] = c o_idx -= 1 return ''.join(o) if __name__ == '__main__': print("str_rev :\n\ttime: ", timeit("str_rev('vimal')", setup="from __main__ import str_rev")) print("\tmemory : ", memory_usage((str_rev, {'x':'vimal'} ))) #============================================================================================== print("str_rev_concat :\n\ttime: ", timeit("str_rev_concat('vimal')", setup="from __main__ import str_rev_concat")) print("\tmemory : ", memory_usage((str_rev_concat, {'x': 'vimal'}))) #============================================================================================== print("str_rev_format :\n\ttime: ", timeit("str_rev_format('vimal')", setup="from __main__ import str_rev_format")) print("\tmemory : ", memory_usage((str_rev_format, {'x': 'vimal'}))) #============================================================================================== print("str_rev_reversed :\n\ttime: ", timeit("str_rev_reversed('vimal')", setup="from __main__ import str_rev_reversed")) print("\tmemory : ", memory_usage((str_rev_reversed, {'x': 'vimal'}))) #============================================================================================== print("str_rev_list :\n\ttime: ", timeit("str_rev_list('vimal')", setup="from __main__ import str_rev_list")) print("\tmemory : ", memory_usage((str_rev_list, {'x': 'vimal'}))) ``` ## Output ``` python str_rev : time: 0.20537829999999999 memory : [14.3671875, 14.3671875, 14.3671875] str_rev_concat : time: 0.4885861 memory : [14.375, 14.37890625, 14.37890625] str_rev_format : time: 2.2692567 memory : [14.37890625, 14.37890625, 14.37890625] str_rev_reversed : time: 0.5260423000000003 memory : [14.3828125, 14.3828125, 14.3828125] str_rev_list : time: 0.8645865999999991 memory : [14.38671875, 14.38671875, 14.38671875, 14.38671875] ``` **Note:** _Input for function are given as **vimal** using string of larger length will show dramastic difference in performace_ From above experiment we can conclude that slicing is the best way to reverse a string and using format to reverse a string should be considered as last option.