Clearing serial buffer solved

Riva:
Would it be better to write a small function to clear the buffer instead of doing serial.end/serial.begin as this may fragment memory.

void serialFlush(){

while(Serial.available() > 0) {
    char t = Serial.read();
  }
}

Hi, Can you please explain how will this line of code empty the serial buffer?