PHP rand vs mt_rand vs openssl_random_pseudo_bytes [英] PHP rand vs mt_rand vs openssl_random_pseudo_bytes

查看:37
本文介绍了PHP rand vs mt_rand vs openssl_random_pseudo_bytes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个随机字符串并且正在做一些研究并找到以下链接:

I want to generate a random string and was doing some research and found the following link:

http://golearnphp.com/php-rand-vs-mt_rand-and-openssl_random_pseudo_bytes/

function generateRandom($length) {
    $validCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $myKeeper = '';
    for ($n = 1; $n < $length; $n++) {
        $whichCharacter = rand(0, strlen($validCharacters) - 1);
        $myKeeper .= $validCharacters{$whichCharacter};
    }
    return $myKeeper;
}

function generateRandomdMT($length) {
    $validCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $myKeeper = '';
    for ($n = 1; $n < $length; $n++) {
        $whichCharacter = mt_rand(0, strlen($validCharacters) - 1);
        $myKeeper .= $validCharacters{$whichCharacter};
    }
    return $myKeeper;
}

$start = microtime(true);
echo htmlentities(generateRandom(100000));
var_dump(microtime(true) - $start);

$start = microtime(true);
echo htmlentities(generateRandomdMT(100000));
var_dump(microtime(true) - $start);

$start = microtime(true);
echo htmlentities(substr(base64_encode(openssl_random_pseudo_bytes(100000)), 0, 100000));
var_dump(microtime(true) - $start);

在帖子中,作者说 openssl_random_pseudo_bytes 比其他两个要快得多.这是真的?openssl_random_pseudo_bytes 真的那么快吗?这是测试功能牢度"的正确方法吗?

In the post the writer is saying that openssl_random_pseudo_bytes is significant faster then the other two. Is this true? Is openssl_random_pseudo_bytes really that much faster? Is that the correct way to test the "fastness" of functions?

推荐答案

openssl_random_pseudo_bytes 创建为加密强(检查第二个参数).Rand 是旧的 rand 函数,重复周期很小.MT_Rand 比 rand 好,但不应该被加密系统使用.

openssl_random_pseudo_bytes created to be crypto strong(check the second param). Rand is old rand function with small period of repeating. MT_Rand is better than rand but not supposed to be used by crypto systems.

我敢打赌,执行时间之间的差异不会影响您的应用程序.

I bet that the difference between execution time do not impact on your application.

还有.这些函数返回不同的结果.前两个返回带有 36 个可能字母的字符串.第三个返回带有 64 个可能符号的字符串.两个第一个函数的结果比第三个短.

Also. Those functions return different results. First two return string with 36 possible letters. And third one returns string with 64 possible symbols. Result of two first function is shorter than third one.

如果您正在优化以加快应用程序的速度,您首先应该知道:如何分析您的代码.

If you are making optimization to speed up your application first thing that you should to know: how to profile your code.

这篇关于PHP rand vs mt_rand vs openssl_random_pseudo_bytes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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