제가 인스타그램모듈을 사용하고 있습니다.
인스타그램 모듈에서 모든 이미지를 다운로드 받아 해당 파일을 트위터로 발행하고 있습니다.
결국 이미지의 링크를 /home/qw5414/www/site/files/gginstagram/img~~~ 이렇게 경로를 담은 스트링이 변수에 저장되어야 하는 상황입니다.
실제로 다음과 같이 들어오게 됩니다.
$path = "https://site/files/gginstagram/img~~~~"; 이렇게 경로가 와서 이를 다음과 같이 수정하여 사용하고 있었습니다.
$obj->images = "https://site/files/gginstagram/img~~~~";
$path = "preg_replace('/https:\/\/site\//', '', '$obj->images')";
$path = _XE_PATH_ . $path;
$path 의 최종결과물 "/home/qw5414/www/site/files/gginstagram/img~~~"
이렇게 사용하고 있었습니다.
여기까지 제가 사용하는 코드의 내용이였고요, 문득 preg_replace 을 결국 str_replace 으로 사용해도 괜찮겟다는 생각을 하게 되었습니다. str_replace 는 해당 내용을 찾아서 변경해주는 역할을 하기때문에 정규식이랑 상관없어 보였거든요.
근데 바꾸기 위한 명분으로 삼을 수 있는게 속도일 것 같은데 preg_replace 와 str_replace 와 정규식을 사용하지 않는 선에서 속도차이가 궁금합니다.
아까 다른 분이 str_replace가 더 빠르다는 벤치마크 결과를 올려주셨는데, 그 사이 삭제되었네요.
그 벤치마크는 문자열이 짧은 상황에서 테스트한 것이었고,
문자열이 상당히 긴 상황(수백KB)에서는 preg_replace가 더 빠르게 나왔습니다.
즉, 상황에 따라 다르게 사용하셔야겠습니다.
$html = file_get_contents('https://xetown.com/questions/1376784');
$start = microtime(true);
for($i=0; $i<10000; $i++) $result = str_replace('https://xetown.com', '', $html);
$end = microtime(true);
echo 'str_replace: ' . number_format($end - $start, 3) . '초' . PHP_EOL;
$start = microtime(true);
for($i=0; $i<10000; $i++) $result = preg_replace('/https:\/\/xetown\.com/', '', $html);
$end = microtime(true);
echo 'preg_replace: ' . number_format($end - $start, 3) . '초' . PHP_EOL;
$start = microtime(true);
for($i=0; $i<10000; $i++) $result = strtr($html, ['https://xetown.com' => '']);
$end = microtime(true);
echo 'strtr: ' . number_format($end - $start, 3) . '초' . PHP_EOL;
결과:
str_replace: 3.401초
preg_replace: 0.835초
strtr: 3.477초