While is was writing another answer on StackOverflow, I encountered this very strange behaviour: rb seems to be slower than r :
LINE_NUMBER = 1001
NEW_LINE_2 = ""
NEW_LINE_3 = "".encode()
def test2():
with open("temp.txt", "w") as temp:
temp.write("Foo\n" * 1000)
temp.write("REPLACE ME!\n")
temp.write("Bar\n" * 1000)
with open("temp.txt", "r ") as temp:
lines = temp.read().split("\n")
lines[LINE_NUMBER - 1] = NEW_LINE_2
temp.seek(0)
temp.write("\n".join(lines))
temp.truncate()
def test3():
with open("temp.txt", "wb") as temp:
temp.write(b"Foo\n" * 1000)
temp.write(b"REPLACE ME!\n")
temp.write(b"Bar\n" * 1000)
with open("temp.txt", "rb ") as temp:
lines = temp.read().split(b"\n")
lines[LINE_NUMBER - 1] = NEW_LINE_3
temp.seek(0)
temp.write(b"\n".join(lines))
temp.truncate()
from timeit import repeat
loops = 3_000
count = 1
print(loops * min(repeat("test2()", globals=globals(), repeat=loops, number=count)))
print(loops * min(repeat("test3()", globals=globals(), repeat=loops, number=count)))
Pydroid 3 (Python 3 on Android):
1.5903121093288064
1.754219876602292 # < slower? How?
https://www.online-python.com/
1.2284908443689346
1.0201307013630867 # faster as expected
I thought that decoding and encoding in order to process the file as a string would be slower than processing the bytes itself. Could someone explain me what's going on? I don't understand why it could be slower on Android. Is this a bug maybe?
CodePudding user response:
This is likely hardware/compiler specific. Try running the code on an online compiler (such as: https://www.online-python.com/ ), and results fluctuate or are reversed
CodePudding user response:
r opens a file for both reading and writing. The file pointer is placed at the beginning of the file.
rb opens a file for both reading and writing in binary format. The file pointer is placed at the beginning of the file.