0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript: 判別速度

0
Posted at

例えばある変数vが数値か非数値か判別したいとします。vが取り得る値次第ですが…

if(v>=-1e309);
if(v<=1e309);
if(v.toFixed);
if(v?.toFixed);
if(typeof v==="nubmer");
if(Number.isInteger(v));
if(!(v instanceof Object));

等といった方法があります。v<=1e309(実質v<=Infinity)で事足りる場合が多いのですが、vが数値でない場合は暗黙的型変換が行われるので、低速化を招きます。
しかも型によって変換速度に差があります。同じ型でも中身が巨大になる程低速になる傾向があります。

右より左が高速に比較できる
let s0="a", s1="aa",
	f0=a=>0, f1=Date,
	r0=/a/, r1=/aa/ig;

雑な速度比較program

for(let a of[void 0,0,0n,!0,"",[],{},/ /,a=>0,function(){},class{},Node]){
	let b=1e6,t=Date.now();
	for(;b--;)if(a>=-1e309);
	document.write(Date.now()-t," ");t=new Date;
	for(b=1e6;b--;)if(a?.toFixed);
	document.write(Date.now()-t," ");t=new Date;
	for(b=1e6;b--;)if(typeof a==="nubmer");
	document.write(Date.now()-t," ");t=new Date;
	for(b=1e6;b--;)if(Number.isInteger(a));
	document.write(Date.now()-t," ");t=new Date;
	for(b=1e6;b--;)if(!(a instanceof Object));
	document.write(Date.now()-t,"<hr>")
}

大小比較がぶっちぎりで低速。次に低速なのが数値固有のmethodの存在確認(この場合toFixed)。typeof a==="number"はどんな型でも高速(そもそもこれ以外は用途が限定的過ぎる)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?