Pages

Mar 15, 2015

[Python] Performance enhance by not using range() for comparison

When I was trying to enhance the performance of my Python code, the frist thing I tried is reducing the usage of functions. After I substituted the range() function, the performance had improved a lot, from 404ms to 106ms. The following is the difference between the two versions of the "ZigZag Conversion" code.

404ms
class Solution:
# @return a string
def convert(self, s, nRows):
row_len = 2 * nRows - 2
string = ["" for _ in range(nRows)]
if nRows <= 2:
for i in range(len(s)):
string[i % nRows] += s[i]
else:
for i in range(len(s)):
res = i % row_len
if res in range(nRows, row_len):
string[row_len - res] += s[i]
else:
string[res] += s[i]
output = ""
for i in range(nRows):
output += string[i]
return output
view raw ZigZag_404.py hosted with ❤ by GitHub

106ms
class Solution:
# @return a string
def convert(self, s, nRows):
row_len = 2 * nRows - 2
string = ["" for _ in range(nRows)]
if nRows <= 2:
for i in range(len(s)):
string[i % nRows] += s[i]
else:
for i in range(len(s)):
res = i % row_len
if res >= nRows and res < row_len: # I just replaced the range() function here
string[row_len - res] += s[i]
else:
string[res] += s[i]
output = ""
for i in range(nRows):
output += string[i]
return output
view raw ZigZag_106.py hosted with ❤ by GitHub
Although the performance result depends on the test data, this substitution really improves the entire performance.

No comments:

Post a Comment