简体   繁体   English

多线程中的静态方法

[英]static method in multiple threads

I have a static method 我有一个静态方法

public static void abc(String str) {
    // some code
    str = str + "s";
    // some code
}

Lets assume that this method is called by 100 threads at the same time. 假设同时有100个线程调用此方法。

I think that CPU schedules all these threads to execute this static method. 我认为CPU调度所有这些线程来执行此静态方法。

Lets scale up execute requests. 让我们按比例扩大执行请求。 Now, there are around 100000 threads calling this static method around same time. 现在,大约有100000个线程在同一时间调用此静态方法。

If it is so, this will be a performance overhead (compared to the case where this method is a member of a class). 如果是这样,这将是性能开销(与该方法是类的成员的情况相比)。 Am I correct? 我对么?

  • In theory, a static call can be made slightly more efficient because it doesn't need to do a virtual function lookup, and it can also avoid the overhead of the hidden "this" parameter. 从理论上讲,可以使静态调用的效率稍高一些,因为它不需要执行虚拟函数查找,而且还可以避免隐藏的“ this”参数的开销。
  • In practice, many compilers will optimize this out anyway. 实际上,许多编译器仍然会对此进行优化。
  • The cost of context switching the threads will far exceed any difference due to static vs non-static method calling 由于静态和非静态方法调用,上下文切换线程的成本将远远超过任何差异

From the perspective of the OS's scheduler it doesn't matter whether the method is static or not. 从操作系统的调度程序的角度来看,该方法是否为静态都无关紧要。 At machine level both are just subroutines with some parameters. 在机器级别,这两个都是带有某些参数的子例程。 So unless neither methods are synchronized, there shouldn't be any difference. 因此,除非两种方法都不同步,否则应该没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM