I changed the For loop for a compile
rho = Compile[{{xp, _Real, 1}, {xg, _Real,
1}, {carga, _Real}, {np, _Real}, {ng, _Real}, {dx, _Real}},
n = ng + 1;
\[Rho] = Table[carga*np/(dx*ng), n];
\[Rho][[ng + 1]] = 0;
Do[If[Abs[xp[[i]] - xg[[j]]] <=
dx, \[Rho][[j]] = \[Rho][[j]] -
carga*(1 - (Abs[xp[[i]] - xg[[j]]])/dx)/dx; r += 1, 0] , {i, 1,
np}, {j, 1, ng + 1}];
\[Rho][[1]] = \[Rho][[1]] + \[Rho][[ng + 1]];]
Is it possible to optimize even further?