jueves, 5 de agosto de 2010

Extra Comma

Middle-Square Method vs. Linear Congruential Generator. Two methods for generating random numbers... TIMTOWTDI.

A friend of mine (Puntiel) and I were analyzing a common problem that I have named "Extra Comma". When you elaborate a query to insert several records at once, each input should be separated with comma, except either the first or the last one.

A similar problem also is presented when you should separate several web links with the pipe character '|'.

I think the best way to do this is by using a flag boolean to indicate if it's either the first or the last data, but its easier to indicate the first data.

$isFirstTime = true;
$comma="";
while($data = get_value($rst)) {
$output .= "{$comma} '{$data}'";
if($isFirstTime) {
$comma = ",";
$isFirstTime = false;
}
}

Although I believe that's the ideal way, I don't like how it looks. So, I modified it a little bit.

$comma="";
while($data = get_value($rst)) {
$output .= "{$comma} '{$data}'";
$comma = ",";
}

I chose this one because I didn't find that comma re-assignation as expensive, and also it's easier to read. But my friend prefer this method:

while($data = get_value($rst)) {
$output .= ", '{$data}'";
}
$output = substr($output, 1);

He says that his method is faster than mine. It could be true, because we are not benchmarking anything. But I don't believe that 'substr' is faster than:

while($data = get_value($rst)) {
$output .= ", '{$data}'";
}
$output[0]='';

TIMTOWTDI ("Tim Toady") as you can see. When performance is an issue, these trivialities become important. But, only a benchmarking for both, processes and network, shows when those modifications gives us a real gain.

No hay comentarios:

Publicar un comentario