我现在开始学习着色器(HLSL,GLSL),我看到了很多教程,其中没有创建很多变量,这使阅读变得更加困难。我想知道创建新变量是否会影响着色器的性能。
因此,例如(在 CG 中):
这是
inline float alphaForPos(float4 pos, float4 nearVertex){
return (1.0/_FogMaxRadius)*clamp(_FogRadius - max(length(pos.z - nearVertex.z),length(pos.x - nearVertex.x)), 0.0, _FogRadius)/_FogRadius;
}
比这还快?
inline float alphaForPos(float4 pos, float4 nearVertex){
float distX = length(pos.x - nearVertex.x);
float distZ = length(pos.z - nearVertex.z);
float alpha = 0.0;
alpha = _FogRadius - max(distZ,distX);
alpha = clamp(alpha, 0.0, _FogRadius);
return (1.0/_FogMaxRadius)*alpha/_FogRadius;
}
最佳答案
这不会影响性能。
一切都在一天结束时被内联,编译器的优化部分在优化完成时不会关心单独的变量。
我编译了两个简单的像素着色器,它们调用了这两个函数,并且都在 HLSL 中编译为 9 条指令。
追求可读性并相信编译器会做正确的事情(至少在这一点上 :))。
关于glsl - 在对着色器进行编程时,我应该避免创建多个变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20726741/