检测外部URL的最快方法 [英] Fastest way to detect external URLs

查看:152
本文介绍了检测外部URL的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检测 foo ='http://john.doe'的最快方法是外部 url (与的比较window.location.href ) ?

What's the fastest method to detect if foo='http://john.doe' is an external url (in comparsion to window.location.href)?

推荐答案

我知道正则表达式版本已被接受,但我敢打赌,这比正则表达式的复杂性更快 。 String.replace 非常快。

I know the regex version has already been accepted but I would bet this is "faster" than doing that complex of a regex. String.replace is quite fast.

var isExternal = function(url) {
    var domain = function(url) {
        return url.replace('http://','').replace('https://','').split('/')[0];
    };

    return domain(location.href) !== domain(url);
}



更新



我决定对此进行更多的研究并找到一种使用正则表达式的更快的方法。

Update

I decided to do a little more research on this and found a faster method that uses a Regex.

var isExternalRegexClosure = (function(){
    var domainRe = /https?:\/\/((?:[\w\d-]+\.)+[\w\d]{2,})/i;

    return function(url) {
        function domain(url) {
          return domainRe.exec(url)[1];  
        }

        return domain(location.href) !== domain(url);
    }
})();

在IE中,这比 String.replace 方法。但是在Chrome和Firefox中它的速度大约是其两倍。此外,在封闭内部仅定义一次正则表达式而不是仅仅在函数内部通常在Firefox中快30%。

In IE this is slightly faster than the String.replace method. However in Chrome and Firefox it is about twice as fast. Also, defining the Regex only once inside the closure instead of just inside the function normally is about 30% faster in Firefox.

这是一个jsperf ,用于检查确定外部主机名的四种不同方法。

Here is a jsperf examining four different ways of determining an external hostname.

重要的是要注意我试过的每种方法都需要不到1毫秒才能在旧手机上运行。因此,除非您正在进行大批量处理,否则性能可能不应该是您的主要考虑因素。

It is important to note that every method I've tried takes less than 1ms to run even on an old phone. So performance probably shouldn't be your primary consideration unless you are doing some large batch processing.

这篇关于检测外部URL的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆