js UUID

方法一:

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdefghijklmnopqrstuvwxyz";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 34), 1);
    }
    // console.log(s[19], s[19] & 0x3, (s[19] & 0x3) | 0x8)
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
 
    var uuid = s.join("");
    return uuid;
}

方法二:

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}

测试方法一


var temp, i = 0;
function testuuid(){
    let ids = new Set();
    while(i < 9000000){
        ids.add(uuid());
        i++;
    }
    console.log(ids.size)
}
testuuid();

执行900 0000次,执行23.6s,set 集合900 0000,无重复值

图1

测试方法二


var temp, i = 0;
function testuuid(){
    let ids = new Set();
    while(i < 9000000){
        ids.add(guid());
        i++;
    }
    console.log(ids.size)
}
testuuid();

执行900 0000次,执行59.8s,set 集合900 0000,无重复值


图2

其他


还有一些其他方法,自己想吧。

你可能感兴趣的:(js UUID)