Home > database >  What is the difference between sending directly a whole string and sending character by character?
What is the difference between sending directly a whole string and sending character by character?

Time:10-13

In this code.

Why is it :

for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())

and not simply :

connectionSocket.send(outputdata.encode())

I tried the simpler version and it worked too so why doing it character by character?

CodePudding user response:

Using the first approach, you are actually writing the content of the outputdata to a client socket one byte per iteration.

Assuming the actual length of outputdata variable is 100, here's what happens:

  1. range() function is executed once
  2. len() function is executed once
  3. encode() function is executed 100 times
  4. connectionSocket.send() is executed 100 times

So there, you have 1002 invocations in order to send just 100 bytes...

It doesn't look good.

Also, in this particular case it is done by the Python interpreter which also adds a significant overhead to executing those function calls.

Now, using the second approach:

  1. encode() function is executed once
  2. connectionSocket.send() is executed once

Thus, sending 100 bytes of data requires only two invocations in the code you've written.

So, generally, the second approach seems to look all the way better.

Now, for the code you provided neither first, nor the second approach are actually good, because the outputdata is a variable that contains the ENTIRE FILE CONTENT IN MEMORY! (see fp.read() at line 16).

So, fp.read() reads all the content into the process memory and it WILL fail should the size of the file exceed the available memory.

The encode() function creates a byte array as a result of encoding outputdata, effectively doubling it in the same process memory thus doubling the amount of memory needed to actually hold two variables - the outputdata that has been read from the file and the encoded version of it, created and returned by the encode().

P.S. And really, (and I mean, like, REALLY), the code by your link shouldn't ever be used in any kind of production environment under the penalty of death :)

  • Related