Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance or style difference between "if" and "if not"?

Is there a performance difference or style preference between these two ways of writing if statements? It is basically the same thing, the 1 condition will be met only once while the other condition will be met every other time. Should the condition that is met only once be first or second? Does it make a difference performance wise? I prefer the 1st way if the the performance is the same.

data = range[0,1023]
length = len(data)
max_chunk = 10

for offset in xrange(0,length,max_chunk):
    chunk = min(max_chunk,length-offset)
    if chunk < max_chunk:
        write_data(data[offset:])
    else:
        write_data(data[offset:offset+max_chunk])

vs

data = range[0,1023]
length = len(data)
max_chunk = 10

for offset in xrange(0,length,max_chunk):
    chunk = min(max_chunk,length-offset)
    if not chunk < max_chunk:
        write_data(data[offset:offset+max_chunk])
    else:
        write_data(data[offset:])
like image 299
ss41153 Avatar asked Oct 01 '12 19:10

ss41153


1 Answers

In your example, if isn't needed at all:

data = range[0,1023]
length = len(data)
max_chunk = 10

for offset in xrange(0,length,max_chunk):
    write_data(data[offset:offset+max_chunk]) # It works correctly

I think this is the most efficient way in your case.

like image 71
defuz Avatar answered Oct 27 '22 00:10

defuz