javascript中"return obj === void 0"这种写法的原因和好处

本文探讨了JavaScript中使用void0的意义与目的,对比undefined的使用方式,并解释为何选择void0来获取undefined值。
部署运行你感兴趣的模型镜像

学习underscore.js的时候,发现源码中经常出现类似下面的代码:

if (context === void 0) return func;

if (array == null) return void 0;

 

以前没有见过这种写法,到网上搜了一些资料,刚好发现stackoverflow上也有人提出类似的疑问。这里总结归纳下,做个笔记。void其实是javascript中的一个函数,接受一个参数,返回值永远是undefined。可以说,使用void目的就是为了得到javascript中的undefined。Sovoid 0 is a correct and standard way to produce undefined.

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined


 

为什么不直接使用undefined呢?主要有2个原因:

1、使用void 0比使用undefined能够减少3个字节。虽然这是个优势,个人但感觉意义不大,牺牲了可读性和简单性。

>"undefined".length
9
>"void 0".length
6

 

2、undefined并不是javascript中的保留字,我们可以使用undefined作为变量名字,然后给它赋值。

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) //alerts "new value"

Because of this, you cannot safely rely on undefined having the value that you expect。

void, on the other hand, cannot be overidden. void 0 will always return。

我在IE10,Firefox和chrome下测试,遗憾的是没有出现预期的结果。虽然上面的代码没有报错,但是并没有打印出我们期望的"new value"。

 

所以总体来说,使用void 0这种写法意义不大。

 

参考

http://stackoverflow.com/questions/7452341/what-does-void-0-mean

 

http://stackoverflow.com/questions/11409412/how-to-understand-return-obj-void-0-in-the-source-of-underscore

 

 

 


 

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

using System.Collections; using System.Threading.Tasks; using UnityEngine; using System.Diagnostics; using System.IO; using System.Threading; public class OptimizedScreenRecorder : MonoBehaviour { // ====== 性能优化核心配置 ====== private bool $isRecording$ = false; // 原子操作标识符 private string $framesFolderPath$; // 路径复用优化[^1] private int $frameRate$; // 目标帧率 private int $frameCount$ = 0; // 32位计数器(内存优化) private Process $ffmpegProcess$; // FFmpeg进程(延迟初始化) // ====== 对象池实现(RenderTexture)===== public static class RenderTexturePool { private static readonly Queue<RenderTexture> $pool$ = new(); public static RenderTexture Get(int width, int height) { if ($pool$.Count > 0) { RenderTexture rt = $pool$.Dequeue(); rt.Create(); // 确保纹理可用 return rt; } return new RenderTexture(width, height, 24) { antiAliasing = 2, wrapMode = TextureWrapMode.Clamp }; } public static void Release(RenderTexture rt) { if (rt != null) { rt.Release(); $pool$.Enqueue(rt); } } } // ====== 屏幕录制启动方法 ====== public void StartRecording(string folderPath, int fps) { $framesFolderPath$ = Path.Combine(folderPath, "FrameCache"); // 路径复用[^1] $frameRate$ = fps; $frameCount$ = 0; // ✅ 异步创建目录(避免主线程阻塞) Task.Run(() => { if (!Directory.Exists($framesFolderPath$)) Directory.CreateDirectory($framesFolderPath$); }); $isRecording$ = true; StartCoroutine(CaptureFrames()); } // ====== 帧捕获协程(核心优化) ====== private IEnumerator CaptureFrames() { Application.runInBackground = true; // 必需后台执行 // ✅ 从对象池获取资源 RenderTexture rt = RenderTexturePool.Get(Screen.width, Screen.height); Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false); // ✅ 命令缓冲优化(异步渲染) CommandBuffer cmd = new CommandBuffer { name = "AsyncCapture" }; cmd.Blit(Camera.main.targetTexture, rt); Graphics.ExecuteCommandBufferAsync(cmd, ComputeQueueType.Background); while ($isRecording$) { yield return new WaitForEndOfFrame(); // ✅ 异步帧处理 Task.Run(() => { RenderTexture.active = rt; tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); tex.Apply(); byte[] bytes = tex.EncodeToPNG(); string framePath = Path.Combine($framesFolderPath$, $"frame_{$frameCount$++:00000}.png"); File.WriteAllBytes(framePath, bytes); // 异步写入[^3] }); } // ✅ 资源回收 RenderTexturePool.Release(rt); Destroy(tex); } // ====== FFmpeg视频编码(进程优化) ====== public void StartEncoding(string outputPath) { string ffmpegPath = Application.streamingAssetsPath + "/ffmpeg.exe"; // ✅ 异步进程启动 ThreadPool.QueueUserWorkItem(_ => { ProcessStartInfo startInfo = new ProcessStartInfo(ffmpegPath) { Arguments = $"-framerate {$frameRate$} -i {$framesFolderPath$}/frame_%05d.png -c:v libx264 -preset fast {outputPath}", RedirectStandardInput = true, CreateNoWindow = true, UseShellExecute = false }; $ffmpegProcess$ = new Process { StartInfo = startInfo }; $ffmpegProcess$.Start(); $ffmpegProcess$.WaitForExit(); }); } // ====== 安全停止与资源清理 ====== public void SafeStopRecording(bool deleteFrames = true) { $isRecording$ = false; // ✅ FFmpeg优雅退出 if ($ffmpegProcess$ != null) { $ffmpegProcess$.StandardInput.Write("q"); // FFmpeg退出指令 if (!$ffmpegProcess$.WaitForExit(5000)) $ffmpegProcess$.Kill(); $ffmpegProcess$.Dispose(); // 避免资源泄漏[^1] } // ✅ 异步资源清理 if (deleteFrames) Task.Run(() => Directory.Delete($framesFolderPath$, true)); } } using System.Collections; using System.Threading.Tasks; using UnityEngine; using System.Diagnostics; using System.IO; using System.Threading; public class OptimizedScreenRecorder : MonoBehaviour { // ====== 性能优化核心配置 ====== private bool $isRecording$ = false; // 原子操作标识符 private string $framesFolderPath$; // 路径复用优化[^1] private int $frameRate$; // 目标帧率 private int $frameCount$ = 0; // 32位计数器(内存优化) private Process $ffmpegProcess$; // FFmpeg进程(延迟初始化) // ====== 对象池实现(RenderTexture)===== public static class RenderTexturePool { private static readonly Queue<RenderTexture> $pool$ = new(); public static RenderTexture Get(int width, int height) { if ($pool$.Count > 0) { RenderTexture rt = $pool$.Dequeue(); rt.Create(); // 确保纹理可用 return rt; } return new RenderTexture(width, height, 24) { antiAliasing = 2, wrapMode = TextureWrapMode.Clamp }; } public static void Release(RenderTexture rt) { if (rt != null) { rt.Release(); $pool$.Enqueue(rt); } } } // ====== 屏幕录制启动方法 ====== public void StartRecording(string folderPath, int fps) { $framesFolderPath$ = Path.Combine(folderPath, "FrameCache"); // 路径复用[^1] $frameRate$ = fps; $frameCount$ = 0; // ✅ 异步创建目录(避免主线程阻塞) Task.Run(() => { if (!Directory.Exists($framesFolderPath$)) Directory.CreateDirectory($framesFolderPath$); }); $isRecording$ = true; StartCoroutine(CaptureFrames()); } // ====== 帧捕获协程(核心优化) ====== private IEnumerator CaptureFrames() { Application.runInBackground = true; // 必需后台执行 // ✅ 从对象池获取资源 RenderTexture rt = RenderTexturePool.Get(Screen.width, Screen.height); Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false); // ✅ 命令缓冲优化(异步渲染) CommandBuffer cmd = new CommandBuffer { name = "AsyncCapture" }; cmd.Blit(Camera.main.targetTexture, rt); Graphics.ExecuteCommandBufferAsync(cmd, ComputeQueueType.Background); while ($isRecording$) { yield return new WaitForEndOfFrame(); // ✅ 异步帧处理 Task.Run(() => { RenderTexture.active = rt; tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); tex.Apply(); byte[] bytes = tex.EncodeToPNG(); string framePath = Path.Combine($framesFolderPath$, $"frame_{$frameCount$++:00000}.png"); File.WriteAllBytes(framePath, bytes); // 异步写入[^3] }); } // ✅ 资源回收 RenderTexturePool.Release(rt); Destroy(tex); } // ====== FFmpeg视频编码(进程优化) ====== public void StartEncoding(string outputPath) { string ffmpegPath = Application.streamingAssetsPath + "/ffmpeg.exe"; // ✅ 异步进程启动 ThreadPool.QueueUserWorkItem(_ => { ProcessStartInfo startInfo = new ProcessStartInfo(ffmpegPath) { Arguments = $"-framerate {$frameRate$} -i {$framesFolderPath$}/frame_%05d.png -c:v libx264 -preset fast {outputPath}", RedirectStandardInput = true, CreateNoWindow = true, UseShellExecute = false }; $ffmpegProcess$ = new Process { StartInfo = startInfo }; $ffmpegProcess$.Start(); $ffmpegProcess$.WaitForExit(); }); } // ====== 安全停止与资源清理 ====== public void SafeStopRecording(bool deleteFrames = true) { $isRecording$ = false; // ✅ FFmpeg优雅退出 if ($ffmpegProcess$ != null) { $ffmpegProcess$.StandardInput.Write("q"); // FFmpeg退出指令 if (!$ffmpegProcess$.WaitForExit(5000)) $ffmpegProcess$.Kill(); $ffmpegProcess$.Dispose(); // 避免资源泄漏[^1] } // ✅ 异步资源清理 if (deleteFrames) Task.Run(() => Directory.Delete($framesFolderPath$, true)); } } 不带字符$的版本
10-22
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值