Pular para o conteúdo
Banco de Dados

Conexão com o MYSQL extremamente Lenta

Atualizado em
Capa do artigo: Conexão com o MYSQL extremamente Lenta

Olá Gente!

Hoje me deparei com um caso estranho.

Notei um tempo extremamente alto para conectar via PHP ao MYSQL.

Para testar, criei um arquivo php que apenas se conecta na base e identifica o tempo que demorou:

<?
$TempoBenchmarking = 0;

function TempoCarregamentoInicio()
{
	
	global $TempoBenchmarking;
	
	$TempoBenchmarking = microtime(true);
	
	
}
function TempoCarregamentoAteAqui($Texto = "")
{
	
	global $TempoBenchmarking;

	$Trm = microtime(true) - $TempoBenchmarking;
	
	echo $Texto . " -> " . $Trm . "<br>";

}

TempoCarregamentoInicio();

$conexao 						= mysql_connect("localhost", "XXXXXXX", "XXXXXXX");
mysql_select_db("XXXXXXX", $conexao);

TempoCarregamentoAteAqui("Conexao");
?>

Este simples teste de conexão levou mais de 1 segundo!

Pesquisando as possíveis causas identifiquei que o problema é simples, quando chamamos o host “localhost” o sistema faz o dns reverso para identificar o IP, o que gera um tempo adicional.

Para resolver, basta alterar o “localhost” para “127.0.0.1”:

<?
$TempoBenchmarking = 0;

function TempoCarregamentoInicio()
{
	
	global $TempoBenchmarking;
	
	$TempoBenchmarking = microtime(true);
	
	
}
function TempoCarregamentoAteAqui($Texto = "")
{
	
	global $TempoBenchmarking;

	$Trm = microtime(true) - $TempoBenchmarking;
	
	echo $Texto . " -> " . $Trm . "<br>";

}

TempoCarregamentoInicio();

$conexao 						= mysql_connect("127.0.0.1", "xxxx", "xxx");
mysql_select_db("xxxx", $conexao);
TempoCarregamentoAteAqui("Conexao");
?>

Agora o tempo de conexão reduziu BASTANTE:

Por hoje é só, pessoal! 🛑

Até mais! 👋

Leia também

Node.js

Avaliando o RAG com o Jev como juiz

Como dar nota ao seu RAG em Node.js: um gabarito, a busca do Qdrant medida sem IA e o Jev, da TypeSafe, dizendo se cada resposta é fiel e correta.