A few things:
- Follow pep8 style.
- As others have said,
join
is more efficient. However:
- You can use
'\n'.join
to avoid having to manually append the newline.
- If you are going to be working with lines individually, or are going to save the file, it is better to use a generator and not join at all.
- You can choose how many splits to do. It is much faster to do one split than an arbitrary number as you do. It is faster still to use
partition
, which always does only one split.
- If you are reading the buffer in, again it would be better to iterate over the lines rather than reading the whole thing in at once and splitting.
So, using your code, assuming we need a buffer in and out, this would be a much more efficient approach:
def remove_comments(buffer):
lines = buffer.splitlines()
return '\n'.join(line.partition('--')[0] for line in lines)
However, for example, lets say you want to read a file in, remove comments, then save it again. This would be a far, far more efficient approach:
with open(infile, 'r') as fin, open(outfile, 'w') as fout:
for line in infile:
newline = line.partition('--')[0]
outfile.write(newline+'\n')
Or better yet:
with open(infile, 'r') as fin, open(outfile, 'w') as fout:
outfile.writelines(line.partition('--')[0]+'\n' for line in infile)
They key point to these two approaches is that they only ever keep one line in memory at a time, which saves on memory enormously.
Or, if you want to do some other manipulation on the lines before saving, you could do something like this:
with open(infile, 'r') as fin, open(outfile, 'w') as fout:
newlines1 = (line.partition('--')[0] for line in infile)
newlines2 = (myfunc1(line) for line in newlines1)
newlines3 = (myfunc2(line) for line in newlines2)
fout.writelines(line+'\n' for line in newlines3)
In this case, mfunc1
and myfunc2
are functions that take a single string and return a single string. This approach will apply each operation to each line, but will only ever have one line in memory at a time.
It doesn't really matter what you ultimately do with the lines. You cold convert them to numbers or lists of numbers and do some calculation on them, send them over a network to another machine, or whatever. The point is that by doing it using generators, iterators, and generator expressions, you can save on memory and increase performance by a lot because it only ever has one line in memory at a time.